Re: Benchmarking check to see if array key is set
| From: | Peter Ford | Date: | Thu, 08 Nov 2007 09:06:35 +0000 |
| Subject: | Re: Benchmarking check to see if array key is set | ||
| References: | 1 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-264211@lists.php.net to get a copy of this message | ||
Ford, Mike wrote:
> 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
>
For convenience let's label the cases:
1: if( isset( $myArray[$key] ))
2: if( array key exists( $key, $myArray ))
3: if( $myArray[$key] )
Now, surely 3 is not comparable at all to 1 and 2.
Cases 1 and 2 check that the key exists in the array.
Case 3 does a boolean test on the value referenced by the key. That has several
consequences:
Firstly, if there is no element with key "$key" in the arrray, the interpreter
will throw an error (undefined index ...); this error could be suppressed and
ignored, I suppose.
Secondly, if the value referenced by the key is equivalent to FALSE, then the
test will return FALSE; for example, if you have set $myArray[$key]='' or
$myArray[$key]=0. This could be very confusing.
So if you want to test that the key exists, case 3 is NOT the way to do it. In
fact, you will often want to check that the key exists(with case 1, ideally)
BEFORE using a test of the form of case 3.
Cheers
Pete Ford (no relation, I think, although I do have a cousin called Michael...)