部分参考自: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。
下面是测试代码:
<?php
function 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>";
}
}
} // 用来打印输出结果
<?php
require 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才导致时间太长?
如有哪位知道其中原因,欢迎指教。