|
|
|
|
|
by gramstrong
2673 days ago
|
|
>I think equating ugly with hard-to-read is a common mistake This is just a semantics argument. I can replace "ugly" with "hard-to-read" if you want. I think it's both, in this instance. >Honestly, I find that rating the readability of the object versions vs the switch statement is bikeshedding. I agree in the context of code review, but since this is what we're talking about I figured I'd share my opinion. >Another thing that is worth mentioning is that objects consume memory and allocating memory in JS for this is just wasting orders of magnitudes more cycles and sacrificing throughput for no good reason - other than to try to be clever and avoid an idiomatic and optimizable construct. Premature optimization. If you need to optimize, then do it. Otherwise you should prioritize what you consider understandable and easy-to-write code. I guarantee the vast majority of javascript written would not be ill-affected by this. |
|
A switch statement is a pretty idiomatic choice for the example. Merely knowing more about the low level cost of different options does not make a snippet an optimization.
Examples of actual optimizations (from real world code I've seen) would include using bitmaps, lookup tables, large regexps, tries and binary search. All of these have the property of obscuring the search space in the name of performance, and many come with trade-offs such as increased startup cost or code size. Choosing to use a trie here, for example, without considering its trade offs would be a premature optimization. A switch statement is at worst a refactor that maintains the same algorithm.