note 81047 added to function.in-array

From: Date: Tue, 12 Feb 2008 17:16:17 +0000
Subject: note 81047 added to function.in-array
Groups: php.notes 
Request: Send a blank email to php-notes+get-136069@lists.php.net to get a copy of this message
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 ---- Server IP: 193.219.81.76 Probable Submitter: 195.14.188.109 ---- Manual Page -- http://www.php.net/manual/en/function.in-array.php Edit -- https://master.php.net/note/edit/81047 Del: integrated -- https://master.php.net/note/delete/81047/integrated Del: useless -- https://master.php.net/note/delete/81047/useless Del: bad code -- https://master.php.net/note/delete/81047/bad+code Del: spam -- https://master.php.net/note/delete/81047/spam Del: non-english -- https://master.php.net/note/delete/81047/non-english Del: in docs -- https://master.php.net/note/delete/81047/in+docs Del: other reasons-- https://master.php.net/note/delete/81047 Reject -- https://master.php.net/note/reject/81047 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#136069) next »