At Confoo I had an interesting conversation with Guilherme Blanco regarding the fact that in Doctrine 2 they had a performance issue due to usage of array_key_exists() and how it was significantly slower than isset(). His anecdotal example was that doing isset() took 0.5 seconds, while array_key_exists() for the same operation took 5 seconds!
That seemed wrong, given that array_key_exists() simply does a hash table look-up, to determine if the array key exists and the only speed difference would be due to the fact that isset() is a language construct and does not have the overhead of function & parameter processing. So, I've decided to do a quick benchmark using a 5,000 element array.
The above benchmark executed on PHP 5.4 shows that while isset() is 2.5 times faster taking a mere 0.0219 seconds vs 0.0549 seconds taken by array_key_exists(), both operations are extremely quick and take a fraction of a second even when doing 100k operations. Any "optimization" between the calls is purely within the super-micro-micro optimization realm and is not going to make any application measurably faster.
The bottom line is that if your application does not need to distinguish between an array key that does not exist and one whose value happens to be NULL you should use isset() because it happens to be a little faster. However, if a NULL array key value and a non-existant array key are something you need to differentiate between, use array_key_exists() and you don't need to worry about the performance, the function is extremely fast, even in the case of Doctrine 2 that apparently may do as many as 50,000 calls to the function per-request in some cases.
Howdy! Someone in my Facebook group shared this site with us so I came to take a look.
I'm definitely enjoying the information. I'm book-marking and will be tweeting this to my followers! Exceptional blog and superb design.
We noticed this already 9 years ago, granted this was back in PHP 4 days:
It even went into our coding standards: http://www.horde.org/apps/horde/docs/CODING_STANDARDS#existence-checking
I have to admit, we never ran a benchmark again, since this made it into our standard. But then again, we didn't have any reason to change what became second nature to us.
Do you hear that clicking? It is the sound of 1000s of application writers rewriting their key_exists to issets. Because now it's proven it is 10 times faster! So if my app is slow, it's because of that, not because I do a million of them each function call
Very nice post. I just stumbled upon your weblog and wanted
to say that I've truly enjoyed browsing your blog posts. In any case I'll be subscribing in your rss feed and I am hoping you write once more soon!
In easytobook we had an edge case of average half a million loop cycles with 3-4 checks per cycle. We saved significant time not just on this example, but also on sacrificing the magic code in favor of public properties and explicit calls.