From 33599cda60126a7b5c7f9b3cc07d5ae0e3c8232e Mon Sep 17 00:00:00 2001 From: Andre Staltz Date: Tue, 3 May 2016 15:08:45 +0300 Subject: [PATCH] perf(combineLatest): avoid splice and indexOf Speed up CombineLatestSubscriber notifyNext() by making toRespond be a number, not an array which is then spliced or searched with indexOf. We prefill values array with a so-called none object, which is useful for the calculation of the toRespond number. --- src/operator/combineLatest.ts | 21 +++++++++------------ 1 file changed, 9 insertions(+), 12 deletions(-) diff --git a/src/operator/combineLatest.ts b/src/operator/combineLatest.ts index 4c893a73bc..b511e67f6f 100644 --- a/src/operator/combineLatest.ts +++ b/src/operator/combineLatest.ts @@ -8,6 +8,7 @@ import {Subscriber} from '../Subscriber'; import {OuterSubscriber} from '../OuterSubscriber'; import {InnerSubscriber} from '../InnerSubscriber'; import {subscribeToResult} from '../util/subscribeToResult'; +const none = {}; /** * Combines multiple Observables to create an Observable whose values are @@ -190,15 +191,14 @@ export class CombineLatestSubscriber extends OuterSubscriber { private active: number = 0; private values: any[] = []; private observables: any[] = []; - private toRespond: number[] = []; + private toRespond: number; constructor(destination: Subscriber, private project?: (...values: Array) => R) { super(destination); } protected _next(observable: any) { - const toRespond = this.toRespond; - toRespond.push(toRespond.length); + this.values.push(none); this.observables.push(observable); } @@ -209,6 +209,7 @@ export class CombineLatestSubscriber extends OuterSubscriber { this.destination.complete(); } else { this.active = len; + this.toRespond = len; for (let i = 0; i < len; i++) { const observable = observables[i]; this.add(subscribeToResult(this, observable, observable, i)); @@ -226,17 +227,13 @@ export class CombineLatestSubscriber extends OuterSubscriber { outerIndex: number, innerIndex: number, innerSub: InnerSubscriber): void { const values = this.values; + const oldVal = values[outerIndex]; + const toRespond = !this.toRespond + ? 0 + : oldVal === none ? --this.toRespond : this.toRespond; values[outerIndex] = innerValue; - const toRespond = this.toRespond; - if (toRespond.length > 0) { - const found = toRespond.indexOf(outerIndex); - if (found !== -1) { - toRespond.splice(found, 1); - } - } - - if (toRespond.length === 0) { + if (toRespond === 0) { if (this.project) { this._tryProject(values); } else {