Possible Duplicate:
What’s quicker and better to determine if an array key exists in PHP?
suppose I want to store the list of friends I have on memcache.
sometimes i need to search if a user is on my list and sometime i need to fetch all the list of friends.
would you rather
$friends[] = $friend
or
$friends[$friend] = 1;
the rationale is to save as much as ram as decently possible without penalizing speed.
I didn’t find any case study for php 5.3.8 that can help me on my little dilemma:
under load, which is faster to perform?
array_key_exists or in_array? (ie: is foo a friend of bar?)
Also, sometimes i need to fetch the whole list of friends so i need to iterate the whole list in order to build an array of friends. not sure at all about the second method, since I don’t know yet if there will be more array_search|array_key_exists|in_array or fetch of full friends list.
any idea?
array_key_existsis much faster.array_searchmust traverse the whole array, so it is O(n).array_key_existsis a hash table lookup, so it is O(1).See http://en.wikipedia.org/wiki/Big_O_notation if you are new to this concept.
Between
array_key_existsandisset, though both are very fast [O(1)],issetis significantly faster. If this check is happening many thousands of times, you’d want to use isset.It should be noted that they are not identical, though — when the array key exists but the value is
null,issetwill return false andarray_key_existswill return true. If the value may benull, you need to usearray_key_exists.