Skip to content

Commit bdd201c

Browse files
bmeurerbenlesh
authored andcommitted
perf(internal): optimize Subscription#add() for the common case (#4489)
This removes unnecessary checks on the `teardown` parameter upfront, and instead moves these checks into the appropriate branches guarded by the type check. This way we get the same behavior, but with fewer checks and smaller code size. Also optimize adding the child `subscription` to `this._subscriptions` for the common case that there were no previous subscriptions.
1 parent fc84a00 commit bdd201c

File tree

1 file changed

+16
-16
lines changed

1 file changed

+16
-16
lines changed

src/internal/Subscription.ts

Lines changed: 16 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -143,21 +143,13 @@ export class Subscription implements SubscriptionLike {
143143
* list.
144144
*/
145145
add(teardown: TeardownLogic): Subscription {
146-
if (!teardown || (teardown === Subscription.EMPTY)) {
147-
return Subscription.EMPTY;
148-
}
149-
150-
if (teardown === this) {
151-
return this;
152-
}
153-
154-
let subscription = (<Subscription> teardown);
155-
146+
let subscription = (<Subscription>teardown);
156147
switch (typeof teardown) {
157148
case 'function':
158-
subscription = new Subscription(<(() => void) > teardown);
149+
subscription = new Subscription(<(() => void)>teardown);
159150
case 'object':
160-
if (subscription.closed || typeof subscription.unsubscribe !== 'function') {
151+
if (subscription === this || subscription.closed || typeof subscription.unsubscribe !== 'function') {
152+
// This also covers the case where `subscription` is `Subscription.EMPTY`, which is always in `closed` state.
161153
return subscription;
162154
} else if (this.closed) {
163155
subscription.unsubscribe();
@@ -168,13 +160,21 @@ export class Subscription implements SubscriptionLike {
168160
subscription._subscriptions = [tmp];
169161
}
170162
break;
171-
default:
163+
default: {
164+
if (!(<any>teardown)) {
165+
return Subscription.EMPTY;
166+
}
172167
throw new Error('unrecognized teardown ' + teardown + ' added to Subscription.');
168+
}
173169
}
174170

175-
const subscriptions = this._subscriptions || (this._subscriptions = []);
176-
177-
subscriptions.push(subscription);
171+
// Optimize for the common case when adding the first subscription.
172+
const subscriptions = this._subscriptions;
173+
if (subscriptions) {
174+
subscriptions.push(subscription);
175+
} else {
176+
this._subscriptions = [subscription];
177+
}
178178
subscription._addParent(this);
179179

180180
return subscription;

0 commit comments

Comments
 (0)