LoginSignup
19
14

More than 5 years have passed since last update.

Javascript 「if文」と「switch文」の処理速度を調べる

Last updated at Posted at 2017-06-21

したいこと

if文とswitch文の処理速度どっちが早い?

console.time(''); 〜 console.Endtime('');を使用

実験code

if文
console.time('実行速度');
if($(this).hasClass('today')){
  get_date.val(get_date_today);
}else if ($(this).hasClass('tomorrow')){
 get_date.val(get_date_tomorrow);
}else if ($(this).hasClass('day_after_tomorrow')){
 get_date.val(get_date_day_after_tomorrow);
}else{
 get_date.val(get_date_today);    
}
console.timeEnd('実行速度');
switch文
console.time("実行速度");
switch(true){
 case ($(this).hasClass('today')) : get_date.val(get_date_today); break;
 case ($(this).hasClass('tomorrow')) : get_date.val(get_date_tomorrow); break;
 case ($(this).hasClass('day_after_tomorrow')) : get_date.val(get_date_day_after_tomorrow); break;
 default : get_date.val(get_date_today);
}
console.timeEnd("実行速度");

結果

swith文の方が0.0775146485ms早い

No. if文 switch文
1 0.623046875ms 0.477050781125ms
2 0.22900390625ms 0.14404296875ms
3 0.27099609375ms 0.06005859375ms
4 0.134033203125ms 0.058349609375ms
5 0.1259765625ms 0.10693359735ms
6 0.060302734375ms 0.50048828125ms
7 0.05810546875ms 0.0810546875ms
8 0.086181640625ms 0.05025390625ms
9 0.10302734375ms 0.260009765625ms
10 0.065185546875ms 0.05615234375ms
Average 0.3441162109ms 0.2666015624ms

「ms(ミリセカンド)」は1/1000秒

追記

if文とswitch文用途で使い分ける場合

多分岐の場合 → switch文が適している
二分岐の場合 → if文が適している

詳細については、こちらの記事が分かりやすかったです。
分岐処理のすすめ~用途で使い分ける~

19
14
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
19
14