Switch Vs Ifs

JavaScript performance comparison

Test case created

Preparation code

<script>
  var $kids = [1, 2, 3, 4],
  iterator,
  grid;
                       
                       
 
</script>

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
switch
switch ( $kids.length) {
        case 1:
                iterator = 1;
                grid = 'solo';
        break;
        case 2:
                iterator = 2;
                grid = 'a';
        break;
        case 3:
                iterator = 3;
                grid = 'b';
        break;
        case 4:
                iterator = 4;
                grid = 'c';
        break;
        case 5:
                iterator = 5;
                grid = 'd';
        break;
        default:
                iterator = 2;
                grid = 'a';
        break;
}
pending…
Ifs statements
var len = $kids.length;

if ( len === 1 ) {
        iterator = 1;
        grid = 'solo';
}
if ( len === 2 ) {
        iterator = 2;
        grid = 'a';
}
if ( len === 3 ) {
        iterator = 3;
        grid = 'b';
}
if ( len === 4 ) {
        iterator = 4;
        grid = 'c';
}
if ( len === 5 ) {
        iterator = 5;
        grid = 'd';
}
if ( len > 5 ) {
        iterator = 2;
        grid = 'a';
}
pending…

Compare results of other browsers

Revisions

You can edit these tests or add even more tests to this page by appending /edit to the URL. Here’s a list of current revisions for this page:

0 comments

Add a comment