splfixedarray主要是处理数组相关的主要功能,与普通php array不同的是,它是固定长度的,且以数字为键名的数组,,优势就是比普通的数组处理更快。
看看我本机的benchmark测试:
ini_set('memory_limit','12800m');for($size = 10000; $size
结果如下:
testing size: 10000array(): 0.004000186920166splarray(): 0.0019998550415039testing size: 40000array(): 0.017001152038574splarray(): 0.0090007781982422testing size: 160000array(): 0.050002098083496splarray(): 0.046003103256226testing size: 640000array(): 0.19701099395752splarray(): 0.16700983047485testing size: 2560000array(): 0.75704312324524splarray(): 0.67303895950317
通常情况下splfixedarray要比php array快上20%~30%,所以如果你是处理巨大数量的固定长度数组,还是强烈建议使用。
splfixedarray类摘要如下:
splfixedarray implements iterator , arrayaccess , countable { /* 方法 */ public __construct ([ int $size = 0 ] ) public int count ( void ) public mixed current ( void ) public static splfixedarray fromarray ( array $array [, bool $save_indexes = true ] ) public int getsize ( void ) public int key ( void ) public void next ( void ) public bool offsetexists ( int $index ) public mixed offsetget ( int $index ) public void offsetset ( int $index , mixed $newval ) public void offsetunset ( int $index ) public void rewind ( void ) public int setsize ( int $size ) public array toarray ( void ) public bool valid ( void ) public void __wakeup ( void )}
使用splfixedarray:
$arr = new splfixedarray(4);$arr[0] = 'php';$arr[1] = 1;$arr[3] = 'python';//遍历, $arr[2] 为nullforeach($arr as $v) { echo $v . php_eol;}//获取数组长度echo $arr->getsize(); //4//增加数组长度$arr->setsize(5);$arr[4] = 'new one';//捕获异常try{ echo $arr[10];} catch (runtimeexception $e) { echo $e->getmessage();}
