<转>PHP SPL标准库之数据结构固定长度数组(SplFixedArray)

SplFixedArray主要是处理数组相关的主要功能,与普通php array不同的是,它是固定长度的,且以数字为键名的数组,优势就是比普通的数组处理更快。

看看我本机的Benchmark测试

 

  1. ini_set('memory_limit','12800M');
  2.  
  3. for($size = 10000; $size < 10000000; $size *= 4) {
  4. echo PHP_EOL . "Testing size: $size" . PHP_EOL;
  5. for($s = microtime(true), $container = Array(), $i = 0; $i < $size; $i++) $container[$i] = NULL;
  6. echo "Array(): " . (microtime(true) - $s) . PHP_EOL;
  7.  
  8. for($s = microtime(true), $container = new SplFixedArray($size), $i = 0; $i < $size; $i++) $container[$i] = NULL;
  9. echo "SplArray(): " . (microtime(true) - $s) . PHP_EOL;
  10. }

 

结果如下:

 

  1. Testing size: 10000
  2. Array(): 0.004000186920166
  3. SplArray(): 0.0019998550415039
  4.  
  5. Testing size: 40000
  6. Array(): 0.017001152038574
  7. SplArray(): 0.0090007781982422
  8.  
  9. Testing size: 160000
  10. Array(): 0.050002098083496
  11. SplArray(): 0.046003103256226
  12.  
  13. Testing size: 640000
  14. Array(): 0.19701099395752
  15. SplArray(): 0.16700983047485
  16.  
  17. Testing size: 2560000
  18. Array(): 0.75704312324524
  19. SplArray(): 0.67303895950317

 

通常情况下SplFixedArray要比php array快上20%~30%,所以如果你是处理巨大数量的固定长度数组,还是强烈建议使用。

SplFixedArray类摘要如下:

 

  1. SplFixedArray implements Iterator , ArrayAccess , Countable {
  2. /* 方法 */
  3. public __construct ([ int $size = 0 ] )
  4. public int count ( void )
  5. public mixed current ( void )
  6. public static SplFixedArray fromArray ( array $array [, bool $save_indexes = true ] )
  7. public int getSize ( void )
  8. public int key ( void )
  9. public void next ( void )
  10. public bool offsetExists ( int $index )
  11. public mixed offsetGet ( int $index )
  12. public void offsetSet ( int $index , mixed $newval )
  13. public void offsetUnset ( int $index )
  14. public void rewind ( void )
  15. public int setSize ( int $size )
  16. public array toArray ( void )
  17. public bool valid ( void )
  18. public void __wakeup ( void )
  19. }

 

 使用SplFixedArray:

 

  1. $arr = new SplFixedArray(4);
  2. $arr[0] = 'php';
  3. $arr[1] = 1;
  4. $arr[3] = 'python';
  5.  
  6. //遍历, $arr[2] 为null
  7. foreach($arr as $v) {
  8. echo $v . PHP_EOL;
  9. }
  10.  
  11. //获取数组长度
  12. echo $arr->getSize(); //4
  13.  
  14. //增加数组长度
  15. $arr->setSize(5);
  16. $arr[4] = 'new one';
  17.  
  18. //捕获异常
  19. try{
  20. echo $arr[10];
  21. } catch (RuntimeException $e) {
  22. echo $e->getMessage();
  23. } 

转载请注明地址: http://www.phpddt.com/php/SplFixedArray.html 尊重他人劳动成果就是尊重自己!

posted on 2015-10-07 22:04  hahahahahai12  阅读(336)  评论(0)    收藏  举报

导航