PHP性能:复制与参考 [英] PHP Performance : Copy vs. Reference

查看:154
本文介绍了PHP性能:复制与参考的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嘿.今天,我编写了一个小型基准脚本,以比较复制变量和创建变量引用的性能.我期望,例如,创建对大型数组的引用比复制整个数组要慢得多.这是我的基准代码:

Hey there. Today I wrote a small benchmark script to compare performance of copying variables vs. creating references to them. I was expecting, that creating references to large arrays for example would be significantly slower than copying the whole array. Here is my benchmark code:

<?php
    $array = array();

    for($i=0; $i<100000; $i++) {
        $array[] = mt_rand();
    }

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

        $foo = $array;
        recursiveCopy($array, $count+1);
    }

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

        $foo = &$array;
        recursiveReference($array, $count+1);
    }

    $time = microtime(1);
    recursiveCopy($array, 0);
    $copyTime = (microtime(1) - $time);
    echo "Took " . $copyTime . "s \n";


    $time = microtime(1);
    recursiveReference($array, 0);
    $referenceTime = (microtime(1) - $time);
    echo "Took " . $referenceTime . "s \n";

    echo "Reference / Copy: " . ($referenceTime / $copyTime);

我得到的实际结果是,与recursiveCopy一样,recursiveReference大约花费了20倍(!).

The actual result I got was, that recursiveReference took about 20 times (!) as long as recursiveCopy.

有人可以解释这种PHP行为吗?

Can somebody explain this PHP behaviour?

推荐答案

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);
}

这篇关于PHP性能:复制与参考的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆