当前位置: 移动技术网 > IT编程>开发语言>PHP > PHP SPL标准库之SplFixedArray使用实例

PHP SPL标准库之SplFixedArray使用实例

2018年06月23日  | 移动技术网IT编程  | 我要评论

贾玲瘦的照片,煤矿工人工作总结,抓斗

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

看看我本机的benchmark测试:

ini_set('memory_limit','12800m');
 
for($size = 10000; $size < 10000000; $size *= 4) {
  echo php_eol . "testing size: $size" . php_eol;
  for($s = microtime(true), $container = array(), $i = 0; $i < $size; $i++) $container[$i] = null;
  echo "array(): " . (microtime(true) - $s) . php_eol;
 
  for($s = microtime(true), $container = new splfixedarray($size), $i = 0; $i < $size; $i++) $container[$i] = null;
  echo "splarray(): " . (microtime(true) - $s) . php_eol;
}

结果如下:

testing size: 10000
array(): 0.004000186920166
splarray(): 0.0019998550415039
 
testing size: 40000
array(): 0.017001152038574
splarray(): 0.0090007781982422
 
testing size: 160000
array(): 0.050002098083496
splarray(): 0.046003103256226
 
testing size: 640000
array(): 0.19701099395752
splarray(): 0.16700983047485
 
testing size: 2560000
array(): 0.75704312324524
splarray(): 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] 为null
foreach($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();
} 

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网