为什么
用foreach
手动遍历数组,用in_array()
检查needle
是否出现,还是用array_intersect()
?
基准测试
<测试脚本/strong>
<?php
$numbers = range(32, 127);
$numbersLetters = array_map('chr', $numbers);
for (;;) {
$numbersLetters = array_merge($numbersLetters, $numbersLetters);
if (count($numbersLetters) > 10000) {
break;
}
}
$numbers = range(1, count($numbersLetters));
printf("Sample size: %d elements in 2 arrays (%d total) n", count($numbers), count($numbers) + count($numbersLetters));
printf("Benchmarking speed in foreach + in_array() scenario... (this might take a while) ");
shuffle($numbers);
shuffle($numbersLetters);
$t1 = microtime(true);
foreach ($numbers as $number) {
if (in_array($number, $numbersLetters)) {}
}
$t2 = microtime(true);
printf("DONE!n");
printf("Time elapsed: %.5f n", $t2 - $t1);
// =============================------------===============================
printf("Benchmarking speed with array_intersect...");
shuffle($numbers);
shuffle($numbersLetters);
$t1 = microtime(true);
array_intersect($numbers, $numbersLetters);
$t2 = microtime(true);
printf("DONE!n");
printf("Time elapsed: %.5f n", $t2 - $t1);
输出strong>
Sample size: 12288 elements in 2 arrays (24576 total)
Benchmarking speed in foreach + in_array() scenario... (this might take a while) DONE!
Time elapsed: 3.79213
Benchmarking speed with array_intersect...DONE!
Time elapsed: 0.05765
小提琴:http://ideone.com/OZ2Idf
结论 array_intersect
比foreach
+ in_array
快得多
为什么array_intersect
更快?
- 与PHP 相反,在C代码中计算交集。
- 在内部,Zend引擎在计算交集之前对数组进行排序(为什么处理排序数组更快?)