If-else vs. switch vs. lookup table
JavaScript performance comparison
Preparation code
<script>
Benchmark.prototype.setup = function() {
function ifElseTest(stuff) {
if(stuff === 1) {
return "food";
} else if (stuff === 2) {
return "building";
} else if (stuff === 3) {
return "furniture";
} else if (stuff === 4) {
return "driving";
} else if (stuff === 5) {
return "drink";
} else if (stuff === 6) {
return "nothing";
}
};
function switchTest(stuff) {
switch (stuff) {
case 1:
return "food";
break;
case 2:
return "building";
break;
case 3:
return "furniture";
break;
case 4:
return "driving";
break;
case 5:
return "drink";
break;
case 6:
return "nothing";
break;
}
};
var lookupTable = {
1: function() {
return "food";
},
2: function() {
return "building";
},
3: function() {
return "furniture";
},
4: function() {
return "driving";
},
5: function() {
return "drink";
},
6: function() {
return "nothing";
}
};
};
</script>
Test runner
Warning! For accurate results, please disable Firebug before running the tests. (Why?)
Java applet disabled.
| Test | Ops/sec | |
|---|---|---|
if else |
|
pending… |
switch |
|
pending… |
lookup table |
|
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:
- Revision 1: published by Tobias Otte
- Revision 2: published by Luís Couto
- Revision 3: published by Jonatas Miguel
- Revision 4: published by Jonatas Miguel
- Revision 5: published by Jonatas Miguel
- Revision 6: published
- Revision 7: published
- Revision 8: published
- Revision 9: published
- Revision 10: published
- Revision 11: published
- Revision 12: published
0 comments