proposal-signals icon indicating copy to clipboard operation
proposal-signals copied to clipboard

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

Open NullVoxPopuli opened this issue 1 year ago • 5 comments

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?

NullVoxPopuli avatar May 07 '24 15:05 NullVoxPopuli

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

ritschwumm avatar May 07 '24 19:05 ritschwumm

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:

  • FireFox (Dev, 127.0a1)
    • just false is faster (which is what I would expect)
  • Chrome: (124.0.6367.118)
    • calling a function is faster than just having false, which is very surprising

Node and Bun are basically the same: image

NullVoxPopuli avatar May 07 '24 19:05 NullVoxPopuli

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 😣

ziadkh0 avatar May 10 '24 14:05 ziadkh0

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.

littledan avatar May 13 '24 19:05 littledan

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.

dead-claudia avatar May 20 '24 10:05 dead-claudia