且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

PHP性能:复制与参考

更新时间:2022-06-27 02:40:56

PHP很可能会实现复制时复制用于其数组,这意味着当您复制"一个数组时,PHP不会完成物理复制内存的所有工作,直到您修改了其中一个副本并且您的变量不再可以引用相同的内部表示形式.

PHP will very likely implement copy-on-write for its arrays, meaning when you "copy" an array, PHP doesn't do all the work of physically copying the memory until you modify one of the copies and your variables can no longer reference the same internal representation.

因此,您的基准测试从根本上来说是有缺陷的,因为您的recursiveCopy函数实际上并未复制该对象.如果这样做的话,您将很快耗尽内存.

Your benchmarking is therefore fundamentally flawed, as your recursiveCopy function doesn't actually copy the object; if it did, you would run out of memory very quickly.

尝试以下操作:通过分配给数组的一个元素,您可以强制PHP 实际上进行复制.您会发现您很快就会耗尽内存,因为在递归函数达到其最大深度之前,所有副本都不会超出范围(并且不会进行垃圾回收).

Try this: By assigning to an element of the array you force PHP to actually make a copy. You'll find you run out of memory pretty quickly as none of the copies go out of scope (and aren't garbage collected) until the recursive function reaches its maximum depth.

function recursiveCopy($array, $count) {
    if($count === 1000)
        return;

    $foo = $array;
    $foo[9492] = 3; // Force PHP to copy the array
    recursiveCopy($array, $count+1);
}