Using object literal rather than switch statement

if-statement, javascript, loops, switch-statement

Solution

You're likely seeing effects of scale: A switch statement is `O(n)`, while a hash table lookup (presumably used to find methods in object literals) is (amortized) `O(1)`. But Big-O measures only accurately describe how performance scales over really big inputs. In your test, it's not surprising that five `if` statements are faster than a hash table lookup.

So basically: How many keys are you going to have? If you've only got five keys, you'll hit on average 2.5 per lookup, which you've shown to be faster than a single hash table lookup. But what if you have 500? That's an average of 250 `if` statements - still versus a single hash lookup. The hash table (object literal) approach is almost assuredly better at that point.

But the ultimate answer? everybody hates to hear this, but it's the only authoritative way: Do the benchmark with your actual production code. It's a pain, but then you know for sure.

Hope that helps!

PS: This is leaving aside all considerations of coding style preference, but I really don't want to get into that...

Problem

There is a lot of discussions and comments about best practices in switch and if/else statements. I have seen people saying that we all should use object literal instead of switch when it is possible. So I've reproduced this case and I went trough a little and simple test between a switch : ``` (function(test){ var bar; switch(bar) { case 1: bar = 'red'; break; case 2: bar = 'blue'; break; case 3: bar = 'yellow'; break; case 4: bar = 'green'; break; case 5: bar = 'black'; break; } return bar; })(5); ``` and passing trough an object literal : ``` (function(test){ return { 1: 'red', 2: 'blue', 3: 'yellow', 4: 'green', 5: 'black' }[ test ]; })(5); ``` After running this test, it seems evident that the switch statement is faster than calling the tested value in an object literal. Is my test wrong ? What should I consider before using one or another method in this case ? Or maybe opinionated comments I've seen about this subject are just wrong and I should not try to bypass fundamentals...

Original source