4

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

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.