5 ms·
≥Object lookups are fast and they're faster as their size grow It's difficult to imagine a switch large enough where the performance difference would matter, b
by EpicEng 8y ago
≥Object lookups are fast and they're faster as their size grow
It's difficult to imagine a switch large enough where the performance difference would matter, but this ignores the memory required to store the lookup in the first place. In all of the switch examples a switch is more straightforward.
In the latter examples (see the Boolean example) we now perform the lookup twice if the value is present. I feel like this is just another case of "use the right tool for the job".
- greglindahl 8y agoA lot of C/C++/Fortran compilers have very well-developed handling for huge switch statements because of generated code. Interpreters and other finite state machines, etc etc.
- EpicEng 8y agoSure. I didn't want to go into too much depth on performance here as I'm a C and C<variant> guy primarily, only writing JS when I have to.
- bastawhiz 8y agoIf you're using an object, the object and any closures in it also need to be constructed on each execution. If the object is large, you're not just doing a lookup, you're constructing a full map object. With a switch, there is no up-front allocation, case expressions are only evaluated if the case is reached, and the body of a case is only evaluated if the case is executed. The lookups are hardly the performance concern.
- hombre_fatal 8y agoOf course, you could allocate once by extracting it or with an IIFE + closure from TFA's functions. lookup = (() => { map = { a: 1, b: 2 } return (key) => map[key] || 'not found' })()
- bastawhiz 8y agoThat helps solve the performance issue within one execution of the surrounding function, but if the surrounding function is called many times, you're more introducing more closures and more indirection. Switch statements involve no allocation. Closures objects, and function calls aren't free.
- hombre_fatal 8y agoWell, in my example, the surrounding function is instantly invoked once and cannot be invoked again. It's merely a useful pattern to avoid polluting the top-level with extraction.
- detaro 8y agoI seem to remember some colleagues once getting performance problems because V8 didn't optimize switch-cases with more than 512(?) cases. Which was easily solved by adding an "if", splitting the table into two, until V8 removed or raised that limit.