if-else,switch或基于map的条件的性能 [英] Performance of if-else, switch or map based conditioning

查看:119
本文介绍了if-else,switch或基于map的条件的性能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道javascript中以下条件结构实现的性能。

I was wondering about the performances of the following implementations of conditional structs in javascript.

方法1:

 if(id==="camelCase"){
    window.location.href = "http://www.thecamelcase.com";
}else if (id==="jsFiddle"){
    window.location.href = "http://jsfiddle.net/";
}else if (id==="cricInfo"){
    window.location.href = "http://cricinfo.com/";
}else if (id==="apple"){
    window.location.href = "http://apple.com/";
}else if (id==="yahoo"){
    window.location.href = "http://yahoo.com/";
}           

方法2:

switch (id) {
case 'camelCase':
    window.location.href = "http://www.thecamelcase.com";
    break;
case 'jsFiddle':
    window.location.href = "http://www.jsfiddle.net";
    break;
case 'cricInfo':
    window.location.href = "http://www.cricinfo.com";
    break;
case 'apple':
    window.location.href = "http://www.apple.com";
    break;
case 'yahoo':
    window.location.href = "http://www.yahoo.com";
    break;

}

方法3

var hrefMap = {
camelCase : "http://www.thecamelcase.com",
jsFiddle: "http://www.jsfiddle.net",
cricInfo: "http://www.cricinfo.com",
apple: "http://www.apple.com",
yahoo: "http://www.yahoo.com"
};
window.location.href = hrefMap[id];

方法4

window.location.href = {
    camelCase : "http://www.thecamelcase.com",
    jsFiddle: "http://www.jsfiddle.net",
    cricInfo: "http://www.cricinfo.com",
    apple: "http://www.apple.com",
    yahoo: "http://www.yahoo.com"
}[id];

可能方法3和4可能具有几乎相同的性能,但只是发布以确认。

Probably Method 3 and 4 might have almost the same performance but just posting to confirm.

推荐答案

根据 JSBen.ch 测试,开关设置是所提供方法中最快的(Firefox 8.0和Chromium 15)。

According to this JSBen.ch test, the switch setup is the fastest out of the provided methods (Firefox 8.0 and Chromium 15).

方法3和4的速度稍慢,但几乎不可察觉。显然,if-elseif方法明显较慢(FireFox 8.0)。

Methods 3 and 4 are slightly less fast, but it's hardly noticeable. Clearly, the if-elseif method is significantly slower (FireFox 8.0).

Chromium 15中的相同测试并未显示这些方法之间的性能差异。事实上,if-elseif方法似乎是Chrome中最快的方法。

The same test in Chromium 15 does not show significant differences in performance between these methods. In fact, the if-elseif method seems to be the fastest method in Chrome.

我有再次运行测试用例 ,另外还有10个条目。 hrefmap(方法3和4)显示出更好的性能。

I have run the test cases again, with 10 additional entries. The hrefmap (methods 3 and 4) show a better performance.

如果要在函数中实现compare方法,方法3肯定会获胜:将地图存储在变量,稍后引用此变量,而不是重构它。

If you want to implement the compare method in a function, method 3 would definitely win: Store the map in a variable, and refer to this variable at a later point, instead of reconstructing it.

这篇关于if-else,switch或基于map的条件的性能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆