If-else vs. switch vs. lookup table
JavaScript performance comparison
Preparation code
<script>
Benchmark.prototype.setup = function() {
function ifElseTest(stuff) {
if(stuff === "pizza") {
return "food";
} else if (stuff === "house") {
return "building";
} else if (stuff === "table") {
return "furniture";
} else if (stuff === "car") {
return "driving";
} else if (stuff === "water") {
return "drink";
} else if (stuff === "air") {
return "nothing";
}
};
function switchTest(stuff) {
switch (stuff) {
case "pizza":
return "food";
break;
case "house":
return "building";
break;
case "table":
return "furniture";
break;
case "car":
return "driving";
break;
case "water":
return "drink";
break;
case "air":
return "nothing";
break;
}
};
var lookupTable = {
"pizza": function() {
return "food";
},
"house": function() {
return "building";
},
"table": function() {
return "furniture";
},
"car": function() {
return "driving";
},
"water": function() {
return "drink";
},
"air": 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