Skip to content

Commit b30df9d

Browse files
committed
refactor: flushPending improve performance
1 parent 4a309e8 commit b30df9d

File tree

1 file changed

+26
-6
lines changed

1 file changed

+26
-6
lines changed

src/vanilla/internals.ts

Lines changed: 26 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -394,11 +394,19 @@ const BUILDING_BLOCK_ensureAtomState: EnsureAtomState = (store, atom) => {
394394

395395
const BUILDING_BLOCK_flushCallbacks: FlushCallbacks = (store) => {
396396
const buildingBlocks = getInternalBuildingBlocks(store)
397-
const mountedMap = buildingBlocks[1]
398397
const changedAtoms = buildingBlocks[3]
399398
const mountCallbacks = buildingBlocks[4]
400399
const unmountCallbacks = buildingBlocks[5]
401400
const storeHooks = buildingBlocks[6]
401+
if (
402+
changedAtoms.size === 0 &&
403+
mountCallbacks.size === 0 &&
404+
unmountCallbacks.size === 0 &&
405+
!storeHooks.f
406+
) {
407+
return
408+
}
409+
const mountedMap = buildingBlocks[1]
402410
const recomputeInvalidatedAtoms = buildingBlocks[13]
403411
const errors: unknown[] = []
404412
const call = (fn: () => void) => {
@@ -413,14 +421,26 @@ const BUILDING_BLOCK_flushCallbacks: FlushCallbacks = (store) => {
413421
call(storeHooks.f)
414422
}
415423
const callbacks = new Set<() => void>()
416-
const add = callbacks.add.bind(callbacks)
417-
changedAtoms.forEach((atom) => mountedMap.get(atom)?.l.forEach(add))
424+
for (const atom of changedAtoms) {
425+
const listeners = mountedMap.get(atom)?.l
426+
if (listeners) {
427+
for (const listener of listeners) {
428+
callbacks.add(listener)
429+
}
430+
}
431+
}
418432
changedAtoms.clear()
419-
unmountCallbacks.forEach(add)
433+
for (const fn of unmountCallbacks) {
434+
callbacks.add(fn)
435+
}
420436
unmountCallbacks.clear()
421-
mountCallbacks.forEach(add)
437+
for (const fn of mountCallbacks) {
438+
callbacks.add(fn)
439+
}
422440
mountCallbacks.clear()
423-
callbacks.forEach(call)
441+
for (const fn of callbacks) {
442+
call(fn)
443+
}
424444
if (changedAtoms.size) {
425445
recomputeInvalidatedAtoms(store)
426446
}

0 commit comments

Comments
 (0)