Javascript switch vs. if ... else if ... else [英] Javascript switch vs. if...else if...else
问题描述
我有几个问题:
- 在switch语句和if语句之间有Javascript的性能差异else if .... else?
- 如果是这样,为什么?
- 是switch的行为,如果... else if ... else不同的浏览器? (FireFox,IE,Chrome,Opera,Safari)
提出此问题的原因似乎是switch语句大约1000s在Firefox中。
已编辑
不幸的是,这不是我的代码。从编译库和我没有访问的代码。生成javascript的方法称为
CreateConditionals(string name,string arrayofvalues,string arrayofActions)
注意arrayofvalues是逗号分隔的列表。
function [name](value){
if(value == [value from array index x]){
[从数组索引x的动作]
}
}
注意:其中[name] =传递到serverside函数的名称
现在我改变了要插入到TextArea的函数的输出,写了一些javascript代码来解析函数并将其转换为一组案例统计。
最后我运行的函数,它运行正常,但性能不同的IE和Firefox。
- 通常是。
- 查看更多信息
- 具有不同的JS处理引擎,但是,在下面的站点上运行测试时,开关总是在大量迭代上执行if,elseif。
真正的测试网站 p>
Guys I have a couple of questions:
- Is there a performance difference in Javascript between a switch statement and an if...else if....else?
- If so why?
- Is the behavior of switch and if...else if...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 convert it to a set of case statments. finally I run the function and it runs fine but performance differs in IE and Firefox.
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.
这篇关于Javascript switch vs. if ... else if ... else的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!