Sy Thanh HO
Sy Thanh HO

Reputation: 51

PHP copy on write process

It is said that PHP uses copy-on-write processes. Then I wander if I run these codes:

$first = 5;
$second = $first;
$first = 5;

Then does it allocate new memory space for $first? Many thanks

Upvotes: 4

Views: 97

Answers (2)

Amit
Amit

Reputation: 1885

The semantic is "copy-on-write" NOT "copy-on-write-only-if-the-value-has-changed".

Also some space for $second is created as soon you declare it. The minimal space required for that variable to exist. At this time the space is NOT allocated for the value that the $first has. So copy on write is at work here; there is no write so no extra space allocated for the value allocated to $first, which is now being assigned to $second.

Then further space is allocated to $second the moment you assign something else to $first. At that time the space is created to hold the copy of the original value in $first

<?php
    echo "<pre>";
    // 10 sets == 100 chars
    $first = "1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890";
    echo memory_get_usage() . "\n";
    $second = $first;
    echo memory_get_usage() . "\n";
    $first = "1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890";
    echo memory_get_usage() . "\n";
    $first = "1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890";
    echo memory_get_usage() . "\n";    

Output

241496
241584
241752
241752

Upvotes: 0

kayo
kayo

Reputation: 642

run this script twice. first time:

echo "<pre>";
$first = 5;
echo memory_get_usage() . "\n";
$second = $first;
echo memory_get_usage() . "\n";
$first = 5;
echo memory_get_usage() . "\n";

result:

333224
333280
333312

second time - just comment one line

echo "<pre>";
$first = 5;
echo memory_get_usage() . "\n";
//$second = $first;
echo memory_get_usage() . "\n";
$first = 5;
echo memory_get_usage() . "\n";

result:

333112
333112
333112

answer: yes, it allocates new memory

Upvotes: 2

Related Questions