部分參考自: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才導致時間太長?
如有哪位知道其中原因,歡迎指教。