Benchmarking check to see if array key is set

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



Consider the following test code:

<?php
  $myArray = array();
  for( $i = 0; $i <= 10000; $i++ )
  {
    $date = microtime( TRUE );
    $key  = rand( $date, $date * rand( 1, 5000 ));
    $myArray[$key] = $key;

  }
  echo '$myArray items created: ' . count( $myArray ) . '<br><br>';

  $startTime = microtime( TRUE );
  $foundCount = 0;
  for( $i = 0; $i <= 10000; $i++ )
  {
    $date = microtime( TRUE );
    $key  = rand( $date, $date * rand( 1, 5000 ));
    if( array key exists( $key, $myArray ))
    {
      $foundCount++;

    }
  }
  $endTime = microtime( TRUE );
  echo 'array key exists took [' . ( $endTime - $startTime ) . '] seconds;
found: [' . $foundCount . '] keys<br><br>';

  $startTime = microtime( TRUE );
  $foundCount = 0;
  for( $i = 0; $i <= 10000; $i++ )
  {
    $date = microtime( TRUE );
    $key  = rand( $date, $date * rand( 1, 5000 ));
    if( isset( $myArray[$key] ))
    {
      $foundCount++;

    }
  }
  $endTime = microtime( TRUE );
  echo 'isset took [' . ( $endTime - $startTime ) . '] seconds; found: [' .
$foundCount . '] keys<br><br>';

  $startTime = microtime( TRUE );
  $foundCount = 0;
  for( $i = 0; $i <= 10000; $i++ )
  {
    $date = microtime( TRUE );
    $key  = rand( $date, $date * rand( 1, 5000 ));
    if( $myArray[$key] )
    {
      $foundCount++;

    }
  }
  $endTime = microtime( TRUE );
  echo 'IF() took [' . ( $endTime - $startTime ) . '] seconds; found: [' .
$foundCount . '] keys<br><br>';
?>

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.

thnx,
Chris

[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux