当前位置:网站首页>Talk about the copy on write mechanism of PHP variables or parameters
Talk about the copy on write mechanism of PHP variables or parameters
2022-06-25 23:47:00 【ndrandy】
php Of copy on wirte( When writing copy ) characteristic , Is a feature used to save memory .Copy on Write In fact, when the value of a variable changes , Will check what the variable points to zval Of ref_count, If ref_count Greater than 1 when , Separation will occur , That is, variables will actually allocate their own independent memory space . If the variable is not written , For example, when a large array is passed to a method as a parameter , And large arrays are only read in methods , Didn't write , This is actually the original memory , No new assignments , This is it. copy on write The significance of .
stay php All data types in the are available during assignment or parameter transfer copy on wirte Mechanism .
stay php5 in the future , Object defaults to “ Implicit reference passing ”, Other data types are passed by value by default ( But there is still copy on wirte Mechanism ), Why do we say that objects are implicitly passed by reference by default . Because only with & The symbol declares the reference passing of the display , It points to zval Of is_ref=true, And implicit reference passing is_ref=false, In fact, the reason is “ Implicit reference passing ” Another reason is : When an object is reassigned within a method, it triggers copy on write, Modify the properties of an object $obj->attr= val It doesn't trigger copy on write,$obj = new_val This will trigger copy on write, and & Reference and reference , Always point to the same memory space , No matter how to modify , Can't trigger copy on write
Next, use the code + How to annotate Briefly describe the variables of each data type copy on wirte trigger
<?php
// /// string Type analysis //
$str = "hello";
$str2 = $str; // here $str and str2 The value of is stored in the same memory space
$str2 = "hi"; /** Now trigger copy on write **/
// /// integer Type analysis
$age = 25;
$number = $age;
$age = 55; /** Now trigger copy on write */
/// /// object Type analysis /
$obj = new stdClass();
$obj->name = "aaa";
$obj2 = $obj; // At this point, the two objects point to the same memory space
$obj2->height = 50; // Modify the properties of an object , Not trigger copy on write, namely :obj === $obj2
// adopt print_r Print obj You can find , modify obj2 Properties of ,obj This attribute is also available , Explain that they point to the same memory space
print_r($obj);
// So here comes the question , When does the object happen copy on write Well ? The answer is that one of the variables re new When .
$obj2 = new stdClass();
$obj2->avatar = "a.png";
// By printing below , It can be analyzed ,obj and obj2 The respective attribute data has been completely independent , It means that copy on write
print_r($obj);
print_r($obj2);
// The result is
/**
stdClass Object
(
[name] => aaa
[height] => 50
)
stdClass Object
(
[avatar] => a.png
)
**/
// If you put 17 The code of the line is changed to $obj2 = &$obj; that obj and obj2 It will never happen copy on write 了 ( namely : Their values are always equal ). This is the real thing "& reference "
// / Next, let's look at how arrays are passed as method parameters , Is there a copy on wirte Mechanism
function processArr(array $arr)
{
$arr1 = ["hello"];
$arr = array_merge($arr, $arr1); // This happens copy on write, here $arr A copy has been separated from the external $arr Has remained independent , This $arr Similar to local variables
print_r(count($arr)); // Output 100000
var_dump(memory_get_usage()); // Output int(8753976), Memory doubled , It means that copy on write, If $arr Read only don't write , No new memory space will be allocated .
echo PHP_EOL;
}
var_dump(memory_get_usage()); // Output int(357080)
$arr = range(1, 99999);
var_dump(memory_get_usage()); // Output int(4555560), Start allocating memory for the array here 4M about
processArr($arr); // The array is passed into the method , without copy on write, Large memory copies will occur
print_r(count($arr)); // Output 99999
var_dump(memory_get_usage()); // Output int(4555560), Method call complete , The memory allocated in the method is freed
// Let's take a look at the object passing copy on write characteristic , stay php5 in the future , Object defaults to " Implicit reference passing "
class Demo
{
public $val;
}
function processObj(Demo $demo)
{
$demo->val = 666;
$demo = new stdClass(); // Now trigger copy on write,$demo Become a temporary variable , And the outside $demo Separation has occurred
$demo->val = "stdClass_val_8";
}
$demo = new Demo();
processObj($demo);
var_dump($demo->val); // Print 666, That is to say processObj In the way , It's triggering copy on write Previous code , Are external to the operation $demo In itself
Through the above code example , It can be summed up :
When passed as a method parameter , By default :
1、 Array $arr[]=append_item, $arr[0]=new_val, $arr=new_arr All three array modification methods trigger copy on write
2、 object $obj->attr = val Not trigger copy on write, and $obj = new_val Will trigger copy on write.( This point is easily confused , It's also because of $obj->attr=val Mode does not trigger copy on write, So that object parameter passing is a bit like reference &)
边栏推荐
- Reprint: detailed explanation of qtablewidget (style, right-click menu, header collapse, multiple selection, etc.)
- Extraction system apk
- Style setting when there is a separator in the qcombobox drop-down menu
- One article explains R & D efficiency! Your concerns are
- 产品经理如何把控产品开发的进度
- php中使用google protobuf协议环境配置
- Px4 simulation basis
- Uniapp - call payment function: Alipay
- Analysis on resource leakage /goroutine leakage / memory leakage /cpu full in go
- DPVS-FullNAT模式keepalived篇
猜你喜欢
UE4 learning records create a role and control its movement
CXF
Anaconda一文入门笔记
Online customer service - charging standards and service provision of third parties
平衡二叉树AVL
The simplest screen recording to GIF gadget in history, licecap, can be tried if the requirements are not high
excel如何实现中文单词自动翻译成英文?这个公式教你了
先序线索二叉树
DPVS-FullNAT模式管理篇
STL教程5-STL基本概念及String和vector使用
随机推荐
c_ uart_ interface_ Example and offboard modes
Mutual conversion of float type data and datetime type data in sqlserver2008
Anaconda一文入门笔记
debezium
C. Planar Reflections-CodeCraft-21 and Codeforces Round #711 (Div. 2)
1.8 billion pixel Mars panorama Ultra HD released by NASA, very shocking
Solve 'tuple' object has no attribute 'lower‘
Analysis and comprehensive summary of full type equivalent judgment in go
InputStream流已经关闭了,但是依旧无法delete文件或者文件夹,提示被JVM占用等
A. Balance the Bits--Codeforces Round #712 (Div. 1)
Can I upload pictures without deploying the server?
对伪类的理解
Object类常用方法
Audio basics and PCM to WAV
Download the latest V80 version of Google Chrome
库项目和App项目中清单文件的包名不要相同
二进制、16进制、大端小端
解析产品开发失败的5个根本原因
Run the dronekit flight control application on Shumei faction under px4-jmavsim software simulation environment
MySQL InnoDB lock knowledge points