note 81047 deleted from function.in-array by danbrown

From: Date: Mon, 08 Jun 2009 21:41:41 +0000
Subject: note 81047 deleted from function.in-array by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-156507@lists.php.net to get a copy of this message
Note Submitter: vidmantas dot norkus at neo dot lt ---- Speed test on frequent search in array <?php //timer class // php 4+ class WDM_Timer{ var $start; function WDM_Timer(){ $this->start=$this->microtime_float(); } function microtime_float(){ list($usec, $sec) = explode(" ", microtime()); return (float)$usec + (float)$sec; } function stop($precision=2){ $precision=(int)$precision; return sprintf("%01.{$precision}f",$this-> microtime_float() - (float)$this->start); } } //lets generate array $ARR1=Array(); for($i=0;$i<10000;$i++){ $key=rand(100000000000000000, 1000000000000000000); $ARR1[]=$key; } ///==================================START TEST 1 $timer=new WDM_Timer(); foreach($ARR1 as $key => $val) in_array($key,$ARR1); echo "TEST1 in_array(\$key,\$ARR) SEARCH. TIME ELAPSED: ".$timer->stop(10)."\n"; ///==================================PREPARE TEST 2 //lets flip array, you can use $ARR2=array_flip($ARR1); $ARR2=Array(); foreach($ARR1 as $key => $val) $ARR2[$val]=''; //==================================START TEST2 $timer=new WDM_Timer(); foreach($ARR2 as $key => $val) isset($ARR[$key]); echo "TEST2 isset(\$ARR[\$key]) SEARCH. TIME ELAPSED: ".$timer->stop(10)."\n"; ?> test results on my server: TEST1 in_array($key,$ARR) SEARCH. TIME ELAPSED: 8.5608828068 TEST2 isset($ARR[$key]) SEARCH. TIME ELAPSED: 0.0020029545

« previous php.notes (#156507) next »