Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

which is faster, array_key_exists or array_search? [duplicate]

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?

like image 814
sathia Avatar asked Dec 06 '11 13:12

sathia


People also ask

Which is faster isset or array_key_exists?

Performance Considerations The takeaway is that isset() is actually faster than array_key_exists() because isset() is actually a language construct, not a function, so it doesn't incur the function call overhead. But both are quite fast, so you probably shouldn't choose one over the other for performance reasons.

What is the difference between In_array and Array_search?

The main difference between both the functions is that array_search() usually returns either key or index whereas in_array() returns TRUE or FALSE according to match found in search.

How do you check if a key exists in an array?

The array_key_exists() function checks an array for a specified key, and returns true if the key exists and false if the key does not exist.

Is key in array PHP?

PHP array_key_exists() FunctionThe array_key_exists() is an inbuilt function of PHP that is used to check whether a specific key or index is present inside an array or not. The function returns true if the specified key is found in the array otherwise returns false.


1 Answers

array_key_exists is much faster. array_search must traverse the whole array, so it is O(n). array_key_exists is 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_exists and isset, though both are very fast [O(1)], isset is 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, isset will return false and array_key_exists will return true. If the value may be null, you need to use array_key_exists.

like image 133
Patrick Fisher Avatar answered Oct 21 '22 10:10

Patrick Fisher