php array_intersect() efficiency

前端 未结 5 1837
旧时难觅i
旧时难觅i 2020-12-03 22:38

consider the below script. two arrays with only three values.when i compare these two arrays using array_intersect(). the result is fast.

    

        
5条回答
  •  离开以前
    2020-12-03 23:17

    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.

提交回复
热议问题