php array_intersect() efficiency

Intersection can be implemented by constructing a set of the searched values in the second array, and looking up in a set can be made so fast that it takes essentially constant time on average. Therefore, the runtime of the whole algorithm can be in O(n).

Alternatively, one can sort the second array (in O(n log n)). Since looking up in a sorted array has a runtime in O(log n), the whole algorithm should then have a runtime in O(n log n).

According to a (short, unscientific) test I just ran, this seems to be the case for php’s array_intersect:

Performance of array_intersect

Here’s the code I used to test it. As you can see, for an input size as small as 1000, you don’t need to worry.

Leave a Comment