From 8d1cb5c89ecd9ee7da397d125c7b7c86f7ac29ff Mon Sep 17 00:00:00 2001 From: Brian Takita Date: Thu, 11 Jul 2019 03:14:29 -0400 Subject: [PATCH] Breadth first calling of subscribers in store dependency tree. Optimize performance by using subscriber_queue. --- src/runtime/store/index.ts | 35 ++++++++++++----------------------- 1 file changed, 12 insertions(+), 23 deletions(-) diff --git a/src/runtime/store/index.ts b/src/runtime/store/index.ts index c5bbb052cf..25c37945c6 100644 --- a/src/runtime/store/index.ts +++ b/src/runtime/store/index.ts @@ -44,6 +44,8 @@ export interface Writable extends Readable { /** Pair of subscriber and invalidator. */ type SubscribeInvalidateTuple = [Subscriber, Invalidator]; +const subscriber_queue = []; + /** * Creates a `Readable` store that allows reading by subscription. * @param value initial value @@ -69,7 +71,15 @@ export function writable(value: T, start: StartStopNotifier = noop): Writa value = new_value; if (stop) { // store is ready subscribers.forEach((s) => s[1]()); - subscribers.forEach((s) => s[0](value)); + const run_queue = !subscriber_queue.length; + subscribers.forEach(s => subscriber_queue.push(s, value)); + if (run_queue) { + let s; + while (s = subscriber_queue.shift()) { + const val = subscriber_queue.shift(); + s[0](val); + } + } } } } @@ -128,10 +138,6 @@ export function derived( const auto = fn.length < 2; - const subscribers: Array> = []; - const invalidators: Array> = []; - let value: T = initial_value; - const store = readable(initial_value, (set) => { let inited = false; const values: StoresValues = [] as StoresValues; @@ -147,11 +153,6 @@ export function derived( const result = fn(single ? values[0] : values, set); if (auto) { set(result as T); - const dirty = safe_not_equal(value, result); - value = result as T; - if (!dirty) { - subscribers.forEach(s => s(value)); - } } else { cleanup = is_function(result) ? result as Unsubscriber : noop; } @@ -166,7 +167,6 @@ export function derived( } }, () => { - run_all(invalidators); pending |= (1 << i); }), ); @@ -182,18 +182,7 @@ export function derived( return { subscribe(run: Subscriber, invalidate: Invalidator = noop): Unsubscriber { - subscribers.push(run); - invalidators.push(invalidate); - - const unsubscribe = store.subscribe(run, invalidate); - - return () => { - const index = invalidators.indexOf(invalidate); - if (index !== -1) { - invalidators.splice(index, 1); - } - unsubscribe(); - }; + return store.subscribe(run, invalidate); } }; }