admin管理员组文章数量:1130730
Guys I have a couple of questions:
- Is there a performance difference in JavaScript between a
switch
statement and anif...else
? - If so why?
- Is the behavior of
switch
andif...else
different across browsers? (FireFox, IE, Chrome, Opera, Safari)
The reason for asking this question is it seems that I get better performance on a switch
statement with approx 1000s cases in Firefox.
Edited Unfortuantly 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
CreateConditionals(string name, string arrayofvalues, string arrayofActions)
note arrayofvalues
is a comma separated list.
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
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 case
statements.
finally I run the function and it runs fine but performance differs in IE and Firefox.
Guys I have a couple of questions:
- Is there a performance difference in JavaScript between a
switch
statement and anif...else
? - If so why?
- Is the behavior of
switch
andif...else
different across browsers? (FireFox, IE, Chrome, Opera, Safari)
The reason for asking this question is it seems that I get better performance on a switch
statement with approx 1000s cases in Firefox.
Edited Unfortuantly 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
CreateConditionals(string name, string arrayofvalues, string arrayofActions)
note arrayofvalues
is a comma separated list.
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
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 case
statements.
finally I run the function and it runs fine but performance differs in IE and Firefox.
Share Improve this question edited Aug 1, 2024 at 16:21 user17726418 2,3668 gold badges16 silver badges33 bronze badges asked May 27, 2010 at 16:30 John HartsockJohn Hartsock 86.8k23 gold badges134 silver badges146 bronze badges 4- 1 I would suggest a code sample to examine what's optimal. I mean, there's gotta be a reason you're asking this, right? – jcolebrand Commented May 27, 2010 at 16:34
- 1 Please post what you're up to, because there are very few cases in my long experience for which I'd say a 100-case switch statement or a 100-part if/else series was a good idea. – Pointy Commented May 27, 2010 at 16:40
- sorry guys not 100s but thousands of conditions – John Hartsock Commented May 27, 2010 at 17:04
- 4 Everyone, thanks for the input. But my problem wasnt actually the difference between the if and swith statments. It was the code running inside the statement. +1 to all of you for your help. Sorry for the inconvienience. Sometimes you just need to talk things out with another person to find the solution. – John Hartsock Commented May 27, 2010 at 17:34
10 Answers
Reset to default 143Answering 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.
Test site
Sometimes it's better to use neither. For example, in a "dispatch" situation, Javascript lets you do things in a completely different way:
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.
The performance difference between a switch
and if...else if...else
is 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 switch
while 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.
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.
Pointy's answer suggests the use of an object literal as an alternative to switch
or if
/else
. I like this approach too, but the code in the answer creates a new map
object every time the dispatch
function is called:
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 map
contains 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:
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();
}
Other than syntax, a switch can be implemented using a tree which makes it O(log n)
, while a if/else has 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?
- 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.
Is there a preformance difference in Javascript between a switch statement and an if...else if....else?
I don't think so, switch
is useful/short if you want prevent multiple if-else
conditions.
Is the behavior of switch and if...else if...else different across browsers? (FireFox, IE, Chrome, Opera, Safari)
Behavior is same across all browsers :)
It turns out that if
-else
is generally faster than switch.
See jsPerf.app — Switch vs. if/else — Benchmark created by Jason on January 12, 2012 for more information.
- 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
For people still looking for this in end 2024.
Benchmark : https://jsben.ch/B1k4I
Reasons to use if/else if instead of switch :
- Minify better due to ? : shorthand
- Usually prevent one useless level of indent
- Avoid weird behavior with switch variable scope being shared across all cases
Unless you're dealing with a huge number of cases in a performance critical application, and can't use objects, no point using switch i think
本文标签: cross browserDifferences between switch and ifelse in JavaScriptStack Overflow
版权声明:本文标题:cross browser - Differences between switch and if-else in JavaScript - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736759221a1951456.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论