3 ms·
If 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 look
by bastawhiz 8y ago
If 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.