note 70652 added to control-structures.switch

From: Date: Mon, 23 Oct 2006 11:38:19 +0000
Subject: note 70652 added to control-structures.switch
Groups: php.notes 
Request: Send a blank email to php-notes+get-118998@lists.php.net to get a copy of this message
In regard to what dohpaz at kennethpaul dot com wrote. If you ever have time you may want to test out having a premade associative array with the required elements eaqualing the needed value. Then assign the value based on the array element. in dohpaz's month example it would look like this: <?php $arr_month = array( 'January' => 1, 'February' => 2, 'March' => 3, 'April' => 4, 'May' => 5, 'June' => 6, 'July' => 7, 'August' => 8, 'September' => 9, 'October' => 10, 'November' => 11, 'December' => 12); foreach($arr_month as $k => $v) {$arr_month[substr($k,0,3)] = $v;} // autogen a 3 letter version //note that the overall size will be 23 because May will only exist once $month = 'Jan'; $month = $arr_months[$month]; echo $month; // outputs: 1 ?> It beats a switch in this case. I did some benchmarking. The array system is faster than the switch system. Here were my average time results of 1000 itterations of assigning the numeric value to the month. The value was randomized between each itteration (this was not added to the benchmark value), so each method was simulated with various data to stress different points. array: 'avg' => 1.09958648682E-6 switch: 'avg' => 4.32157516479E-6 switch (true): 'avg' => 6.90913200378E-6 Contrary to what dohpaz suggested I found that a normal switch was faster than a switch(true) version. I repeated these test several times to take into acount server load variations. The ratios were always consistent. The array way is notably faster. ---- Server IP: 66.163.161.117 Probable Submitter: 74.118.201.181 ---- Manual Page -- http://www.php.net/manual/en/control-structures.switch.php Edit -- https://master.php.net/note/edit/70652 Del: integrated -- https://master.php.net/note/delete/70652/integrated Del: useless -- https://master.php.net/note/delete/70652/useless Del: bad code -- https://master.php.net/note/delete/70652/bad+code Del: spam -- https://master.php.net/note/delete/70652/spam Del: non-english -- https://master.php.net/note/delete/70652/non-english Del: in docs -- https://master.php.net/note/delete/70652/in+docs Del: other reasons-- https://master.php.net/note/delete/70652 Reject -- https://master.php.net/note/reject/70652 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#118998) next »