Skip to content

Instantly share code, notes, and snippets.

@a-yasui
Created October 17, 2013 03:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save a-yasui/7019012 to your computer and use it in GitHub Desktop.
Save a-yasui/7019012 to your computer and use it in GitHub Desktop.
PHP5.5/PHP5.3 にて、連想配列とSwitchのパフォーマンス比較。結果的にはswitchの方が速く、PHP55の方が速いですよっと。
$ /usr/local/Cellar/php53/5.3.27/bin/php switch_or_array.php
start arr ... Finish: 10.038110971451
start sw ... Finish: 6.0564711093903
$ /usr/local/Cellar/php55/5.5.4/bin/php switch_or_array.php
start arr ... Finish: 8.5129861831665
start sw ... Finish: 5.0694410800934
<?php
/** Switch と Array どっちが速いかファイ!! */
function sw ($data) {
switch ($data) {
case 'aa': return 1;
case 'bb': return 2;
case 'cc': return 3;
case 'dd': return 3;
case 'ee': return 3;
case 'ff': return 3;
case 'gg': return 3;
case 'hh': return 3;
case 'ii': return 3;
case 'jj': return 3;
case 'kk': return 3;
case 'll': return 3;
case 'mm': return 3;
case 'nn': return 3;
case 'oo': return 3;
case 'pp': return 3;
case 'qq': return 3;
case 'rr': return 3;
case 'ss': return 3;
case 'tt': return 3;
case 'uu': return 3;
case 'vv': return 3;
case 'ww': return 3;
case 'xx': return 3;
case 'yy': return 3;
case 'zz': return 3;
}
}
function arr ($data) {
$arr = array(
'aa'=> 3,
'bb'=> 3,
'cc'=> 3,
'dd'=> 3,
'ee'=> 3,
'ff'=> 3,
'gg'=> 3,
'hh'=> 3,
'ii'=> 3,
'jj'=> 3,
'kk'=> 3,
'll'=> 3,
'mm'=> 3,
'nn'=> 3,
'oo'=> 3,
'pp'=> 3,
'qq'=> 3,
'rr'=> 3,
'ss'=> 3,
'tt'=> 3,
'uu'=> 3,
'vv'=> 3,
'ww'=> 3,
'xx'=> 3,
'zz'=> 3,
);
return $arr[$data];
}
function do_run ($fnc) {
$start = microtime(true);
echo "start $fnc ... ";
// 100万回ループ
for ($i = 0; $i < 1000000; $i++) {
$fnc("qq");
}
echo "Finish: " . (microtime(true) - $start) . "\n";
}
do_run("arr");
do_run("sw");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment