Javascript 开关与 if...else if...else
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2922948/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript switch vs. if...else if...else
提问by John Hartsock
Guys I have a couple of questions:
伙计们,我有几个问题:
- Is there a performance difference in JavaScript between a
switchstatement and anif...else? - If so why?
- Is the behavior of
switchandif...elsedifferent across browsers? (FireFox, IE, Chrome, Opera, Safari)
- JavaScript 中的
switch语句和if...else?之间是否存在性能差异? - 如果是为什么?
- 浏览器之间的
switch和行为是否if...else不同?(火狐、IE、Chrome、Opera、Safari)
The reason for asking this question is it seems that I get better performance on a switchstatement with approx 1000s cases in Firefox.
问这个问题的原因似乎是我switch在 Firefox 中使用大约 1000 个案例的语句获得了更好的性能。
EditedUnfortuantly this is not my code the Javascript is being produced serverside from a compiled library and I have no access to the code. The method that is producing the javascript is called
编辑不幸的是,这不是我的代码,Javascript 是从编译的库在服务器端生成的,我无法访问该代码。调用生成 javascript 的方法
CreateConditionals(string name, string arrayofvalues, string arrayofActions)
note arrayofvaluesis a comma separated list.
注意arrayofvalues是逗号分隔的列表。
what it produces is
它产生的是
function [name] (value) {
if (value == [value from array index x]) {
[action from array index x]
}
}
Note: where [name]= the name passed into the serverside function
注意: where [name]= 传入服务器端函数的名称
Now I changed the output of the function to be inserted into a TextArea, wrote some JavaScript code to parse through the function, and converted it to a set of casestatements.
现在我把函数的输出改成一个TextArea,写了一些JavaScript代码来解析这个函数,然后转换成一组case语句。
finally I run the function and it runs fine but performance differs in IE and Firefox.
最后我运行该函数,它运行良好,但在 IE 和 Firefox 中的性能不同。
采纳答案by Tommy
Answering in generalities:
一般性回答:
- Yes, usually.
- See More Info Here
- Yes, because each has a different JS processing engine, however, in running a test on the site below, the switch always out performed the if, elseif on a large number of iterations.
- 是的,通常。
- 在此处查看更多信息
- 是的,因为每个都有不同的 JS 处理引擎,但是,在下面的站点上运行测试时,开关总是在大量迭代中执行 if、elseif。
回答by Pointy
Sometimes it's better to use neither. For example, in a "dispatch" situation, Javascript lets you do things in a completely different way:
有时两者都不使用会更好。例如,在“调度”情况下,Javascript 让您以完全不同的方式做事:
function dispatch(funCode) {
var map = {
'explode': function() {
prepExplosive();
if (flammable()) issueWarning();
doExplode();
},
'hibernate': function() {
if (status() == 'sleeping') return;
// ... I can't keep making this stuff up
},
// ...
};
var thisFun = map[funCode];
if (thisFun) thisFun();
}
Setting up multi-way branching by creating an object has a lot of advantages. You can add and remove functionality dynamically. You can create the dispatch table from data. You can examine it programmatically. You can build the handlers with other functions.
通过创建对象来设置多路分支有很多优点。您可以动态添加和删除功能。您可以从数据创建调度表。您可以以编程方式检查它。您可以使用其他函数构建处理程序。
There's the added overhead of a function call to get to the equivalent of a "case", but the advantage (when there are lots of cases) of a hash lookup to find the function for a particular key.
有一个函数调用的额外开销来获得相当于一个“案例”,但是哈希查找的优势(当有很多案例时)可以找到特定键的函数。
回答by Guffa
The performance difference between a switchand if...else if...elseis small, they basically do the same work. One difference between them that may make a difference is that the expression to test is only evaluated once in a switchwhile it's evaluated for each if. If it's costly to evaluate the expression, doing it one time is of course faster than doing it a hundred times.
aswitch和a 之间的性能差异if...else if...else很小,它们基本上做同样的工作。它们之间可能有所不同的一个区别是,要测试的表达式只switch偶尔计算一次,它会为每个if. 如果计算表达式的成本很高,那么执行一次当然比执行一百次要快。
The difference in implementation of those commands (and all script in general) differs quite a bit between browsers. It's common to see rather big performance differences for the same code in different browsers.
这些命令(以及一般的所有脚本)的实现差异在浏览器之间存在很大差异。在不同浏览器中看到相同代码的相当大的性能差异是很常见的。
As you can hardly performance test all code in all browsers, you should go for the code that fits best for what you are doing, and try to reduce the amount of work done rather than optimising how it's done.
由于您几乎无法在所有浏览器中对所有代码进行性能测试,因此您应该选择最适合您正在执行的工作的代码,并尝试减少已完成的工作量而不是优化其完成方式。
回答by Jon Benedicto
- If there is a difference, it'll never be large enough to be noticed.
- N/A
- No, they all function identically.
- 如果有差异,它永远不会大到引起注意。
- 不适用
- 不,它们的功能都相同。
Basically, use whatever makes the code most readable. There are definitely places where one or the other constructs makes for cleaner, more readable and more maintainable. This is far more important that perhaps saving a few nanoseconds in JavaScript code.
基本上,使用任何使代码最具可读性的东西。肯定有一些地方可以使用一种或另一种构造使更清洁、更易读和更易于维护。这比在 JavaScript 代码中节省几纳秒更重要。
回答by Evan Carroll
Other than syntax, a switch can be implemented using a tree which makes it O(log n), while a if/elsehas to be implemented with an O(n)procedural approach. More often they are both processed procedurally and the only difference is syntax, and moreover does it really matter -- unless you're statically typing 10k cases of if/else anyway?
除了语法之外,可以使用生成它的树来实现 switch O(log n),而if/else必须使用O(n)过程方法来实现。更常见的是,它们都是按程序处理的,唯一的区别是语法,而且这真的很重要——除非你静态输入 10k 个 if/else 案例?
回答by Michael Geary
Pointy's answersuggests the use of an object literal as an alternative to switchor if/else. I like this approach too, but the code in the answer creates a new mapobject every time the dispatchfunction is called:
Pointy 的回答建议使用对象文字作为switchor if/的替代else。我也喜欢这种方法,但是map每次dispatch调用该函数时,答案中的代码都会创建一个新对象:
function dispatch(funCode) {
var map = {
'explode': function() {
prepExplosive();
if (flammable()) issueWarning();
doExplode();
},
'hibernate': function() {
if (status() == 'sleeping') return;
// ... I can't keep making this stuff up
},
// ...
};
var thisFun = map[funCode];
if (thisFun) thisFun();
}
If mapcontains a large number of entries, this can create significant overhead. It's better to set up the action map only once and then use the already-created map each time, for example:
如果map包含大量条目,这会产生大量开销。最好只设置一次动作映射,然后每次都使用已经创建的映射,例如:
var actions = {
'explode': function() {
prepExplosive();
if( flammable() ) issueWarning();
doExplode();
},
'hibernate': function() {
if( status() == 'sleeping' ) return;
// ... I can't keep making this stuff up
},
// ...
};
function dispatch( name ) {
var action = actions[name];
if( action ) action();
}
回答by Sarfraz
Is there a preformance difference in Javascript between a switch statement and an if...else if....else?
Javascript 中的 switch 语句和 if...else if....else 之间是否存在性能差异?
I don't think so, switchis useful/short if you want prevent multiple if-elseconditions.
我不这么认为,switch如果您想防止多种if-else情况,则很有用/很短。
Is the behavior of switch and if...else if...else different across browsers? (FireFox, IE, Chrome, Opera, Safari)
switch 和 if...else if...else 的行为是否因浏览器而异?(火狐、IE、Chrome、Opera、Safari)
Behavior is same across all browsers :)
所有浏览器的行为都相同:)
回答by Koen
- Workbenching might result some very small differences in some cases but the way of processing is browser dependent anyway so not worth bothering
- Because of different ways of processing
- You can't call it a browser if the behavior would be different anyhow
- 在某些情况下,工作台可能会导致一些非常小的差异,但处理方式无论如何都取决于浏览器,因此不值得打扰
- 由于处理方式不同
- 如果行为会有所不同,则不能将其称为浏览器
回答by sidonaldson
It turns out that if-else if generally faster than switch
事实证明 if-else if 通常比 switch 快

