What is Copy On Write?
Answer: When copying an object, you do not actually copy the original object to another location in the memory. Instead, you set a pointer in the memory mapping table of the new object to point to the location of the source object, and copy the original object to another location in the memory. The Copy-On-Write bit of that piece of memory is set to 1. In this way, when a read operation is performed on a new object, the memory data does not change in any way, and the read operation is performed directly; while when a write operation is performed on the new object, Copy the real object to the new memory address, modify the new object's memory mapping table to point to this new location, and perform write operations at the new memory location.
This technology needs to be used together with virtual memory and paging. The advantage is that when performing a copy operation, it is not a real memory copy, but only creates a pointer, thus greatly improving efficiency. But this is not always true. If after copying new objects, most objects still need to continue writing operations, a large number of paging faults will occur, which is not worth the gain. Therefore, COW is efficient only after copying the new object and performing write operations on a small part of the memory page.
The copy-on-write mechanism is also used in the PHP kernel to avoid memory increase during assignment. For example, when we use the foreach loop body, we can discover the secret, sample code:
When we execute this code we will get the memory usage: 788
When we cancel the comment //$v='aaaaaaaaaaaaaaa'; , the memory usage value is: 840. Note that the memory has increased.
When we rewrite $v in foreach as &$v, regardless of whether the comment on $v in the loop body is commented or not, we can get the memory usage as: 788
This illustrates the intervention of the COW mechanism. When we only use the read operation of $v in the foreach loop, the PHP kernel will point the memory address of the variable $v to the array in $arr. The memory address of the index does not copy the data in the array to the variable $v. At this time, the memory usage is the same as using &$v. But when we write to $v in the loop body, the copy-on-write mechanism is activated. At this time, PHP will re-open a section of memory space to the $v variable, and break the memory address of the array that $v originally pointed to. If it is turned on, the memory will inevitably increase.
Another conclusion can be drawn here: when we read big data, we must pay attention to the impact of memory growth introduced by the COW mechanism. We also avoid unnecessary writing to variables, which can improve code running performance.