4 ms·
> Our third use case involves checking whether the defaultValue is an ordinary value or a function. We could check every time it’s accessed, but instead we’ll a
by gvx 8y ago
> Our third use case involves checking whether the defaultValue is an ordinary value or a function. We could check every time it’s accessed, but instead we’ll assign different function bodies to the proxy’s get key. That way, it’s only checked at (open air quotes) compile time (close air quotes):
The code below that paragraph actually does check on every access, though.
- braythwayt 8y agoHah, yes, I made that change mid-way through to allow for Ruby’s feature where you can mutate the default value of a Hash (a feature I personally have never used), but didn’t update the text. Fix on the way. Thanks for spotting the discrepancy!
- fenomas 8y ago> The code below that paragraph actually does check on every access, though. I could be wrong, but I think a sufficiently clever JS engine (like v8) would remove that check at runtime, by realizing that half of the ternary operator is dead code. (If it's hot code and it gets optimized, anyway).
- braythwayt 8y agoAh, the mythical “sufficiently smart compiler” :-)
- fenomas 8y agoTo clarify I wasn't being hypothetical, I think v8 will optimize out that check today. I phrased it vaguely because I'm not sure whether other engines would as well.
- braythwayt 8y agoIt’s certainly doable. The `defaultValue` parameter is passed by value, so it will never be rebound. The result of using `typeof` on a value never changes in JS, even if the value is modified. So... it should be possible to optimize the check away after the first time.