PHP:in_array()vs array_intersect()性能
作者:互联网
什么,多少,更快 – 用foreach手动迭代数组并使用in_array()或使用array_intersect()检查针的出现?
最佳答案:
基准
测试脚本
<?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);
产量
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
结论
array_intersect比foreach in_array快得多.
为什么array_intersect更快?
>交叉点用C代码计算,而不是PHP
>在内部,Zend引擎sorts the array在计算交叉点之前(why is processing a sorted array faster?)
标签:php,arrays,benchmarking,performance,array-intersect 来源: https://codeday.me/bug/20190516/1114746.html