Re: "isset" or "array_key_exists"?

From: Date: Sat, 18 Feb 2006 09:56:55 +0000
Subject: Re: "isset" or "array_key_exists"?
References: 1  Groups: php.general 
Request: Send a blank email to php-general+get-230680@lists.php.net to get a copy of this message
After a little test, although the results are not conclusive, I would say that isset(), and also that array_key_exists() may even use isset() (or similiar) internally as a first step -let's remember that isset() only does a "fast search" and it returns FALSE if the value is NULL; on the other hand, array_key_exists() returns TRUE even if the value is NULL- I said this (as an hypotesis) because the difference in time when the key exists and when it doesn't is quite big, sometimes about 10 times slower. The script I used to test it was this (it is assumed that any "extra" operation affected both loops equally) <?php
    $arr_test = array( 'key' => array( 1 => -1 ) );
    $num_oprs = 1000;
    $start    = micro_time();
    for ( $i = 0;  $i < $num_oprs;  $i ++ ) {
        if ( isset($arr_test['key'][1]) ) ;
    }
    echo  '<p>isset: ', micro_time() - $start, "</p>\n";
    $start = micro_time();
    for ( $i = 0;  $i < $num_oprs;  $i ++ ) {
        if ( array_key_exists(1, $arr_test['key']) ) ;
    }
    echo  '<p>array_key_exists: ', micro_time() - $start, "</p>\n";
    function micro_time( ) {
        return  preg_replace('/^0(\.\d+) (\d+)$/X',
                             '$2$1', microtime());
    }
?> Nikolay Rastegaev wrote:
Please, answer: what construction works faster: if ( isset ( $result [$i] ["key"] ) )
   {    do something;   }
or if ( array_key_exists ( "key", $result [$i] ) )
   {    do something;   }
? -- Atentamente, J. Rafael Salazar Magaña Innox - Innovación Inteligente Tel: +52 (33) 3615 5348 ext. 205 / 01 800 2-SOFTWARE rsalazar@innox.com.mx http://www.innox.com.mx


« previous php.general (#230680) next »