maettig.com

Thiemos Archiv

In PHP, there is no difference between arrays and hash tables. Arrays are always associative arrays. There are several methods to check if a specific key or value is present in an array. If you know a little bit about data structures you should know that searching for a key should be much more efficient than searching for a value. But how big is the difference? Does it even matter?

My simple benchmark compares in_array( $value, $array ), array_key_exists( $key, $array ) and isset( $array[$key] ) on arrays of different sizes. The number of function calls is always the same (10000), randomly spread so that half of them succeeds and the other half fails. Time is measured using microtime( true ) and rounded to milliseconds.

Array search in PHP: Benchmark to compare in_array, array_key_exists and isset

The result really looks how you think it should look. Searching for a key in a hash table needs constant time, no matter how big the array is. That's exactly why we have hash tables, right? On the other hand, searching for a value in an array needs dramatically more time even on relatively small arrays with only 100 elements. For an array with 10000 elements in_array is more than 100 times slower.

So never ever do in_array( $key, array_keys( $array ) ), that's just stupid.

you shouldn't have drawn that graph on a logarithmic scale. this just reduces the optical impact
Dr. Azrael Tod
Originally I found the graph a bit pointless on a linear scale. But you are right, the impact (it just explodes) is much easier to see on a linear scale. I changed the graph.

PS: I just realized I messed the graph up even more by using a quadratic scale on the X axis. I replaced it again. It's way less impressive now.
Thiemo

Kommentare zu diesem Beitrag können per E-Mail an den Autor gesandt werden.

[ ← Zurück zur Übersicht ]

Impressum & Datenschutz