batch
Edit this pagebatch
is a low-level API that batches updates together.
More precisely, batch(fn)
holds the execution of downstream computations
during the fn
block, executing them all together once the block fn
returns.
Thus, instead of a downstream computation executing after every dependency
update, it will update just once at the end of the batch.
Batching improves performance by avoiding unnecessary recalculation.
Suppose you have a downstream memo down
that depends on
multiple upstream signals up1
, up2
, and up3
:
If you directly update all of the upstream signals outside of batch mode,
then down
will recompute every time.
If instead you update the upstream signals within a batch
, then down
will update only once at the end:
The impact is even more dramatic if you have m downstream computations (memos, effects, etc.) that each depend on n upstream signals. Without batching, modifying all n upstream signals would cause m n updates to the downstream computations. With batching, modifying all n upstream signals would cause m updates to the downstream computations. Given that each update takes at least n time (just to read the upstream signals), this cost savings can be significant. Batching is also especially helpful when the downstream effects include DOM updates, which can be expensive.
Solid uses batch
internally to automatically batch updates for you
in a few cases:
- Within
createEffect
andonMount
(unless they are outside a root) - Within the setter of a store (which can update several properties at once)
- Within array methods (e.g.
Array.prototype.splice
) of a mutable store (which can update several elements at once)
These save you from having to use batch
yourself in many cases.
For the most part, automatic batching should be transparent to you,
because accessing a signal or memo will cause it to update if it is out of date
(as of Solid 1.4). For example:
You can think of batch(fn)
as setting a global "batch mode" variable,
calling the function fn
, and then restoring the global variable to its
previous value.
This means that you can nest batch
calls, and they will form one big batch.
It also means that, if fn
is asynchronous,
only the updates before the first await
will be batched.