Thursday, May 23, 2024
159
rated 0 times [  162] [ 3]  / answers: 1 / hits: 160933  / 14 Years ago, thu, may 27, 2010, 12:00:00

Guys I have a couple of questions:




  1. Is there a performance difference in JavaScript between a switch statement and an if...else?

  2. If so why?

  3. Is the behavior of switch and 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 converted it to a set of case statements.



finally I run the function and it runs fine but performance differs in IE and Firefox.


More From » cross-browser

 Answers
274

Answering in generalities:




  1. Yes, usually.

  2. See More Info Here

  3. 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


[#96666] Monday, May 24, 2010, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jarrettw

Total Points: 300
Total Questions: 98
Total Answers: 103

Location: Saudi Arabia
Member since Mon, Sep 5, 2022
2 Years ago
;