php SPL库是用于解决典型问题(standard problems)的一组接口与类的集合。
本文主要讲定长数组(SplFixedArray)
定长数组可以产生一个正常数组,不同的是,该数组是固定的,数组不能超过长度,它的速度比一般的数组快,定长数组只能是索引数组
定义一个php定长数组(php5.3之后spl已经成为了php内核的一部分,不需要额外安装即可直接使用)$array = new SplFixedArray(5);
$array[0]=1;//定义数组[0]值为1
$array['aaa']=1;//非数字将出错
$array->setSize(10);//修改数组长度
var_dump($array);
一下是spl定长数组与普通数组的效率比对:ini_set('memory_limit','2048M');//防止内存不足,临时更改内存上限
for($size = 1000; $size
echo PHP_EOL . "Testing size: $size" . PHP_EOL;
for($s = microtime(true), $container = Array(), $i = 0; $i
echo "Array(): " . (microtime(true) - $s) . PHP_EOL;
for($s = microtime(true), $container = new SplFixedArray($size), $i = 0; $i
echo "SplArray(): " . (microtime(true) - $s) . PHP_EOL;
}
精确度有差,应该是测试环境,可自测,官方解释是
数据量小1000左右
定长数组写入比php数组快15%,读取快5%;
数据量大,51w条数据时
定长数组写入比php数组快33%,读取快10%;
Testing size: 1000
Array(): 0.00027203559875488
SplArray(): 0.0007932186126709
Testing size: 2000
Array(): 0.00049781799316406
SplArray(): 0.00032687187194824
Testing size: 4000
Array(): 0.0010740756988525
SplArray(): 0.00073003768920898
Testing size: 8000
Array(): 0.0021700859069824
SplArray(): 0.0016100406646729
Testing size: 16000
Array(): 0.004626989364624
SplArray(): 0.0036690235137939
Testing size: 32000
Array(): 0.0095100402832031
SplArray(): 0.0072238445281982
Testing size: 64000
Array(): 0.016055822372437
SplArray(): 0.0084800720214844
Testing size: 128000
Array(): 0.024579048156738
SplArray(): 0.016443967819214
Testing size: 256000
Array(): 0.0483078956604
SplArray(): 0.038909912109375
Testing size: 512000
Array(): 0.10647821426392
SplArray(): 0.074150085449219
Testing size: 1024000
Array(): 0.22535705566406
SplArray(): 0.14000296592712
Testing size: 2048000
Array(): 0.42199611663818
SplArray(): 0.29096388816833
Testing size: 4096000
Array(): 0.88509798049927
SplArray(): 0.81293106079102
本文为仙士可原创文章,转载无需和我联系,但请注明来自仙士可博客www.php20.cn