Reputation: 1091
i've written this code to test the size of some objects in PHP
<?php
class MyClass
{
public $string1="first string";
public $string2="second string";
public $string3="third string";
public function __toString() {
return $this->string;
}
}
function mem() {
return memory_get_usage(false);
}
$before = mem();
$class = new MyClass;
var_dump("new object size: ".(mem() -$before));
$before=mem();
$string = "test";
var_dump("string size: ".(mem() -$before));
$before=mem();
$objcopy = $class;
var_dump("object copy size: ".(mem() -$before));
$before=mem();
$objref = &$class;
var_dump("object reference size: ".(mem() -$before));
and this is the output in my system:
string(20) "new object size: 188"
string(15) "string size: 80"
string(20) "object copy size: 44"
string(25) "object reference size: 72"
i'm quite confusing now, why do we have: $class>$string>$objref>$objcopy
shouldn't be instead : $class=$objcopy>$string>$objref ?
$objcopy in fact contains 3 strings inside, instead $string is a single one..
could someone explain me how php handle memory with this kind of object?
thanks in advance.
Upvotes: 0
Views: 101
Reputation: 1091
Yes my question was based on wrong knowledge derived by C++ and other languages reference point of view.
So , after long research , i've created a post on my blog about this argument where i explain in depth how php handle memory.
http://hyperweb2.com/home/blog/2013/10/11/php-reference-vs-copy-vs-clone/
Upvotes: 0
Reputation: 16948
You're observations base on wrong assumptions.
First of all, your $objcopy
is a reference to the same instance as $class
, because Instances are not cloned when assigning them to another variable. Check the manual or add this to your code:
$objcopy->string1 = 'a';
echo $class->string1, "\n";
Second, even if the assignment operator would effectively make them point to different objects, PHP would probably not allocate new memory because it uses copy-on-write optimization, see http://php.net/manual/en/internals2.variables.intro.php.
Finally, you can't expect precise memory informations returned by PHP. It may allocate more than the current statement requires and may implicitly free memory by the garbage collector. (Well, at least you can turn that off.)
Upvotes: 1