RE: [PHP] Benchmarking check to see if array key is set
| From: | Ford, Mike | Date: | Tue, 06 Nov 2007 15:28:45 +0000 |
| Subject: | RE: [PHP] Benchmarking check to see if array key is set | ||
| Groups: | php.general | ||
| Request: | Send a blank email to php-general+get-264114@lists.php.net to get a copy of this message | ||
On 06 November 2007 12:57, Christoph Boget wrote:
> Consider the following test code:
[...snip...]
> Running that I found that
>
> if( isset( $myArray[$key] ))
>
> is faster than
>
> if( array key exists( $key, $myArray ))
>
> is faster than
>
> if( $myArray[$key] )
>
> To be honest, I was surprised. I would have thought that if(
> $myArray[$key] ) would have been the fastest way to check. I'm
> wondering if those in the know could explain why it's the slowest and
> also where the discrepancies come from w/r/t the difference in the
> amount of time it takes
> to make each
> check.
OK, I'll take a stab.
Firstly, isset() is a language construct not an actual function, so the only thing your isset() does
is check whether the array element exists.
Next, array_key_exists() is the only one that involves a real function call, so it's going to
bear that cost. However, the function then does a pretty simple test which again only involves
checking whether the key exists, so the function itself is going to be pretty quick.
Finally, the if() is the only one that actually gets the value in $myArray[$key], and then casts it
to Boolean to boot, and the cost of this must therefore outweigh the cost of a function call plus a
check for a key's existence.
I'm certainly not surprised that isset() is the quickest, because it does the simplest test,
but to be honest I'm not sure if I'd have predicted the relative positions of the other
two.
Cheers!
Mike
---------------------------------------------------------------------
Mike Ford, Electronic Information Services Adviser,
JG125, The Headingley Library,
James Graham Building, Leeds Metropolitan University,
Headingley Campus, LEEDS, LS6 3QS, United Kingdom
Email: m.ford@leedsmet.ac.uk
Tel: +44 113 812 4730 Fax: +44 113 812 3211
To view the terms under which this email is distributed, please go to http://disclaimer.leedsmet.ac.uk/email.htm