- Friday, 2014-04-11 21:57
- 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.
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_arrayis more than 100 times slower.
So never ever do
in_array( $key, array_keys( $array ) ), that's just stupid.
Kommentare zu diesem Beitrag können per E-Mail an den Autor gesandt werden.