PHP: in_array() vs array_intersect() performance

痴心易碎 提交于 2020-01-02 03:50:30

问题


What, and how much, is faster - manually iterating over an array with foreach and checking for needle occurrence with in_array(), or using array_intersect()?


回答1:


Benchmark

Test Script

<?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);

Output

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 

Fiddle: http://ideone.com/OZ2Idf

Conclusion

array_intersect is much faster than foreach + in_array.

Why is array_intersect faster?

  • The intersection is computed in C code, as opposed to PHP
  • Internally, Zend engine sorts the array prior to computing the intersection (why is processing a sorted array faster?)


来源:https://stackoverflow.com/questions/40331407/php-in-array-vs-array-intersect-performance

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!