简体   繁体   中英

PHP, does assignment use double memory for a variable?

If I have a large object and assign another variable to that object, does php create two objects, or does it use a pointer internally?

for example:

<?php
$myObject = new Class_That_Will_Consume_Lots_Of_Memory();
$testObject = $myObject;

In this example will i be using 2 x the memory footprint of a Class_That_Will_Consume_Lots_Of_Memory instance or will it be 1 of those and a pointer?

The latter: one object and a pointer/reference (and in fact, here, two pointers/references, since the first is one as well).

To get a new object, use clone .

Related: Are PHP5 objects passed by reference?

Objects in PHP5 are passed by reference, arrays and other types passing is based on Copy on Write technique:

$a = ['a'=>'b'];
$b = $a; // Here we used 1x memory
$b['x'] = 'y'; // Now it become 2x memory

You can use memory_get_usage() to debug memory usage.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM