SplFixedArray和Array的性能测试

来源:互联网 发布:网络理财诈骗案 编辑:程序博客网 时间:2024/05/01 08:16

部分参考自:http://www.php.net/manual/zh/class.splfixedarray.php

PHP文档专门说明:

The SplFixedArray class provides the main functionalities of array. The main differences between a SplFixedArray and a normal PHP array is that the SplFixedArray is of fixed length and allows only integers within the range as indexes. The advantage is that it allows a faster array implementation.

所以在处理大型的、以数字为索引的数组时,应该用SplFixedArray来代替普通Array。

下面是测试代码:

<?phpfunction pr() {    $params = func_get_args();    $env = php_sapi_name();    if ("cli" == $env) {        foreach ($params as $key => $value) {            echo $value;        }    } else {        foreach ($params as $key => $value) {            echo "<pre>";            print_r($value);            echo "</pre>";        }    }} // 用来打印输出结果

<?phprequire dirname(__FILE__)."/function.php";for ($size=1000; $size<=50000000; $size*=2) {    pr(PHP_EOL . "Testing size: $size" . PHP_EOL);     for($s = microtime(true), $container = Array(), $i = 0; $i < $size; $i++) {        $container[$i] = NULL;     }    pr( "Array(): " . (microtime(true) - $s) . PHP_EOL);     for($s = microtime(true), $container = new SplFixedArray($size), $i = 0; $i < $size; $i++) {        $container[$i] = NULL;     }    pr("SplArray(): " . (microtime(true) - $s) . PHP_EOL); }

但是在我的测试机器上,这段代码出现了非常诡异的结果:

暂时想不出来是什么原因:难道是因为虚拟机内存太小,导致最后的SplFixedArray插入时需要不断GC才导致时间太长?

如有哪位知道其中原因,欢迎指教。