react icon indicating copy to clipboard operation
react copied to clipboard

compiler: merge reactive scopes across const StoreLocal

Open josephsavona opened this issue 1 month ago • 1 comments

@jbonta nerd-sniped me into making this optimization during conference prep, posting this as a PR now that keynote is over.

Consider these two cases:

export default function MyApp1({ count }) {
  const cb = () => count;
  return <div onclick={cb}>Hello World</div>;
}

export default function MyApp2({ count }) {
  return <div onclick={() => count}>Hello World</div>;
}

Previously, the former would create two reactive scopes (one for cb, one for the div) while the latter would only have a single scope for the div and its inline callback. The reason we created separate scopes before is that there's a StoreLocal 'cb' = t0 instruction in-between, and i had conservatively implemented the merging pass to not allow intervening StoreLocal instructions.

The observation is that intervening StoreLocals are fine if the assigned variable's last usage is the next scope. We already have a check that the intervening lvalues are last-used at/before the next scope, so it's trivial to extend this to support StoreLocal.

Note that we already don't merge scopes if there are intervening terminals, so we don't have to worry about things like conditional StoreLocal, conditional access of the resulting value, etc.

josephsavona avatar May 16 '24 06:05 josephsavona