php 数组函数性能测试
先看看下面代码运行的结果:
图一:
图二:
图三:
结论:
- 数组越大越难排序
- 先array_keys,再foreach 几乎是单个foreach的2倍时间,且foreach遍历几乎不受数组中存储大小有关,只与索引的个数有关
- array_slice效率很高,但是尽量用小数组切割
- 二维数组中的第二维也是影响排序函数的
所以:
- foreach不用array_keys
- asort,arsort尽量只对一个一维数组操作
附上代码:
echo '<table>'; $a = $b = array(); $t1 = microtime(true); for($alength = 0; $alength < 10; $alength++) { $a[] = $alength; } $t2 = microtime(true); echo "<tr><td>生成一个长度为".$alength."数组:</td><td>".($t2 - $t1)."</td></tr>"; $t1 = microtime(true); asort($a); $t2 = microtime(true); echo "<tr><td>长度为".$alength."的数组asort排序:</td><td>".($t2 - $t1)."</td></tr>"; $t1 = microtime(true); for($i = 0; $i<100000; $i++) { $b[] = $a; } $t2 = microtime(true); echo "<tr><td>".$i."个数据,每个数据中的数组长度为前面生成的数组,其长度是".$alength.":</td><td>".($t2 - $t1)."</td></tr>"; $t1 = microtime(true); $bb = array_keys($b); asort($bb); $t2 = microtime(true); echo "<tr><td>先array_keys后的,".$i."个数据asort长度为".$alength."数组排序:</td><td>".($t2 - $t1)."</td></tr>"; $t1 = microtime(true); arsort($b); $t2 = microtime(true); echo "<tr><td>".$i."个数据arsort长度为".$alength."数组排序:</td><td>".($t2 - $t1)."</td></tr>"; $t1 = microtime(true); foreach ($b as $k=>$v) { } $t2 = microtime(true); echo "<tr><td>".$i."个数据长度为".$alength."数组foreach遍历:</td><td>".($t2 - $t1)."</td></tr>"; $t1 = microtime(true); $kk = array_keys($b); foreach ($kk as $k=>$v) { } $t2 = microtime(true); echo "<tr><td>".$i."个数据长度为".$alength."数组,先array_keys得到索引,再对索引foreach遍历:</td><td>".($t2 - $t1)."</td></tr>"; echo '<br />'; $t1 = microtime(true); $c = array_slice($b,100,100); $t2 = microtime(true); echo "<tr><td>".$i."个数据长度为".$alength."数组array_slice切割:</td><td>".($t2 - $t1)."</td></tr>"; echo '<table>';