PHP Performance question: Faster to leave duplicates in array that will be searched or do array_unique?

后端 未结 3 545
伪装坚强ぢ
伪装坚强ぢ 2020-12-18 01:53

I have code that adds values to an array. The array is later searched in another part of my code. The values that are added to the array are not necessarily unique, so it\'s

相关标签:
3条回答
  • 2020-12-18 01:57

    I think array_unique is slower than in_array but it makes sense if you want to search the array more than one time or if you want to save memory.

    Another option is to use array_flip (which will also drop duplicate keys) and then use isset or array_key_exists since they are way faster than in_array, personally I would go this way.

    0 讨论(0)
  • 2020-12-18 02:02

    This comment was worthy to be promoted to an answer:

    Just found that array_keys(array_flip($array)); is amazingly faster than array_unique();. About 80% faster on 100 element array, 95% faster on 1000 element array and 99% faster on 10,000+ element array.

    Testing here shows that with random (integer) strings which do contain array value repetition, that array_keys(array_flip($array)); method is orders of magnitude faster than other methods.

    0 讨论(0)
  • 2020-12-18 02:05

    array_unique is about sqrt(n) times slower then in_array. But if you optimize the data and search again many times, it can be worth

    PS: notice that

    isset($arr[$key])

    works faster then in_array providing the same result

    0 讨论(0)
提交回复
热议问题