Intermediate LevelPHP 8+
How does PHP Copy-on-Write (CoW) memory management work when passing large arrays?
❓ Interview Prompt: Explain PHP internal zval containers, reference counting (refcount), and Copy-on-Write (CoW) memory allocation.
When you assign a large array or string to a new variable ('$b = $a') or pass it to a function, PHP does NOT make a copy of the memory instantly.
How Copy-on-Write (CoW) Works:
1
Both '$a' and '$b' point to the exact same internal 'zval' memory container.
2
PHP increments the internal 'refcount' pointer ('refcount = 2').
3
Memory is copied ONLY at the exact moment one of the variables is mutated ('$b[0] = "new"').
4
If the variable is read without modification, zero extra memory is consumed!
Code Implementation Example
php
<?php
$largeArray = range(1, 1000000); // Allocates ~30MB RAM
// Assignment does NOT copy memory! (CoW refcount = 2)
$copy = $largeArray;
echo memory_get_usage(); // Memory remains flat (~30MB)!
// Memory copy occurs ONLY when mutating $copy!
$copy[0] = 999;
echo memory_get_usage(); // Memory doubles (~60MB) as CoW triggers!💡Demonstrating PHP Copy-on-Write (CoW) memory behavior during array mutation.
🎯 Interview Key Takeaway
PHP Copy-on-Write delays duplicating array memory until the moment a variable is mutated, optimizing RAM usage.
#Copy-on-Write#Memory#Internals#Intermediate
Back to all PHP 8+ Questions→