John Hartsock John Hartsock - 3 years ago 113
Javascript Question

Javascript switch vs. if...else if...else

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.

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download