note 70652 deleted from control-structures.switch by cmb

From: Date: Sun, 21 Apr 2019 11:52:12 +0000
Subject: note 70652 deleted from control-structures.switch by cmb
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-210645@lists.php.net to get a copy of this message
Note Submitter: sneskid at hotmail dot com ---- 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.

« previous php.notes (#210645) next »