Safari4 で switch〜case を速くする
Safari4 の switch 〜 case 文は、型を統一することで実行速度が大きく変化します。
これを
switch (a) { case "a": case 1: }
こうしましょう。
switch (a) { case "a": case "1": // 1 → "1": }
これだけで、2倍速です。
http://pigs.sourceforge.jp/blog/20100111/20100111.htm
Browser | switch | switch2 | ratio |
Firefox3.0.17 | 548ms | 516ms | 110% |
Firefox3.6RC1(jit) | 78ms | 78ms | 100% |
IE6 | 1640ms | 1640ms | 100% |
IE8 | 1234ms | 1235ms | 100% |
Chrome4.0.266(dev)(jit) | 200ms | 198ms | 100% |
Safari4.0.4(jit) | 208ms | 100ms | 210% |
Opera10.10 | 812ms | 766ms | 110% |
Opera10.50 pre-alpha(jit) | 67ms | 62ms | 110% |
項目が増えると、さらに速度差は開きます。
http://pigs.sourceforge.jp/blog/20100111/more.htm
Browser | mix | string | ratio |
Safari4.0.4(jit) | 2866ms | 136ms | 2100% |
ざっくり 21倍速です。
ベンチマーク
<!doctype html><html><head> <title>bench: switch vs Hash</title><script> window.onload = function() { var hash = { color: 1, backgroundColor: 1, "background-color": 1, top: 2, marginTop: 2, "margin-top": 2, 3: 3 }, ary = ("color,backgroundColor,background-color," + "top,marginTop,margin-top,3").split(","); document.body.innerHTML += navigator.userAgent + "<p>" + [ switchBench(100000, ary), switchBench2(100000, ary), "" ].join("ms</p><p>") + "</p>"; function switchBench(loop, ary) { var now = +new Date; var rv = 0, n = 0, i = 0, j, jz = ary.length; for (; i < loop; ++i) { for (j = 0; j < jz; ++j) { v = ary[j]; switch (ary[j]) { case "color": case "backgroundColor": case "background-color": n = 1; break; case "top": case "marginTop": case "margin-top": n = 2; break; case 3: // ここ n = 3; break; default: n = 0; } rv += n; } } return (+new Date) - now; } function switchBench2(loop, ary) { var now = +new Date; var rv = 0, n = 0, i = 0, j, jz = ary.length; for (; i < loop; ++i) { for (j = 0; j < jz; ++j) { v = ary[j]; switch (ary[j]) { case "color": case "backgroundColor": case "background-color": n = 1; break; case "top": case "marginTop": case "margin-top": n = 2; break; case "3": // ここ n = 3; break; default: n = 0; } rv += n; } } return (+new Date) - now; } } </script></head><body></body></html>