Reputation: 10210
Does PHP provide any Lazy copy concept?
My believe is that Lazy copy is not implemented in PHP(infact is it a correct terminology?) while Lazy loading can be implement on object properties by simple flag property of an object.
I came across a answer(Please see) on SO with a large number of upvote, a part of explanation seems to be completely wrong.
He is saying unless $b is not changed $a will keep only reference of $b.
$b=3;
$a=$b;
// $a points to $b, equals to $a=&$b
$b=4;
// now PHP will copy 3 into $a, and places 4 into $b
I can understand Lazy loading. Keep a flag property in object and whenever we try to get the property of an object just initialize all properties from DB. Pseudo code looks like this:
private function GetAccessor($member) {
if($this->isLoaded != true) {
$this->Load(); //initialize or copy all properties from DB - LAZY LOADING
}
....
Note: php.net also doesn't mentioned lazy copy anywhere.
Upvotes: 0
Views: 423
Reputation: 40820
Well yes PHP does this. This is an optimization strategy the php interpreter does for you. The concept is also known as "copy on write".
Suppose you have a reeeaaaallly large string
$a = "lllloooooong [imagine another million characters here]";
And then you want to copy that:
$b = $a;
Then chances are, that doing this copy operation was never necessary, because either you never altered $a or $b meaning that both variables have the same value at all the time and thus you could just use $a OR $b reducing your memory consumption by 50% and saving you that copy operation.
So the PHP-interpreter will on the first operation $b = $a
assume, that you probably will never change $a or $b and it will not do any copying but instead it memorizes that $b has the same data as $a. As soon as you change $b or as soon as you change $a, the interpreter's previous assumption is proven as wrong and the interpreter will do the copying after all.
But this behaviour is an operation that happens behind the scenes. You don't see it, you can't influence it directly and it does not have any effect that you must be aware of in order to code PHP. Instead you can always work as if variables would be copied immediately.
Upvotes: 4
Reputation: 255005
My believe is that Lazy copy is not implemented
It is implemented and it is called COW (Copy-on-Write)
See:
Upvotes: 4