tc39 / proposal-signals

A proposal to add signals to JavaScript.
MIT License
2.95k stars 54 forks source link

Shorthand idea: `false` instead of `() => false` for `equals` #218

Open NullVoxPopuli opened 3 weeks ago

NullVoxPopuli commented 3 weeks ago

in options for both Signal.State and Signal.Computed, an equals function is allowed to be passed to change how "dirtiness" is calculated -- it could be an optimization to allow false instead of requiring a function to then call every time -- we could skip part of the dirtying algo.

thoughts?

ritschwumm commented 3 weeks ago

might be premature optimization - i'd guess a modern JIT would inline a constant function returning false and eliminate what's left of it.

NullVoxPopuli commented 3 weeks ago

that is an interesting point about JIT -- I made a little test to see what happens (perf.link)

I only have these two browsers atm:

Node and Bun are basically the same: image

zaygraveyard commented 3 weeks ago

Modifying @NullVoxPopuli's test (perf.link) to include a loop results in the false version being faster in FireFox (Dev, 126.0b1), Google Chrome (124.0.6367.202), and Safari (17.4.1) on an M1 MacBook Air running macOS 14.4.1

PS: Not sure if my version is benchmarking the right thing though, benchmarking is hard 😣

littledan commented 2 weeks ago

This is about more than the speed of calling the function: the signals system can have a more clear understanding of what's going on if it knows that it will always be false.

dead-claudia commented 1 week ago

And to add on to that, if it's faster to always call, an engine will set its internal equals field to a private pre-optimized global function that always returns false.

Not that I even slightly find this likely, though. Not when it's only 3-4 instructions and 1 load total compared to well over a dozen plus a multiply indirect call.