Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Prefer for..of loops to forEach for perf #32

Merged
merged 6 commits into from
Jan 22, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
58 changes: 43 additions & 15 deletions src/strongbus.ts
Original file line number Diff line number Diff line change
Expand Up @@ -528,19 +528,21 @@ export class Bus<TEventMap extends Events.EventMap = Events.EventMap> implements
public get listeners(): ReadonlyMap<EventKeys<TEventMap>|Events.WILDCARD, ReadonlySet<EventHandlers.GenericHandler>> {
if(!this._cachedGetListersValue) {
const listenerCache = new Map(this.ownListeners);
this._delegates.forEach((_, delegate) => {
delegate.listeners.forEach((delegateListeners, event) => {
for(const delegate of this._delegates.keys()) {
for(const [event, delegateListeners] of delegate.listeners) {
if(!delegateListeners.size) {
return;
continue;
}
let listeners = listenerCache.get(event);
if(!listeners) {
listeners = new Set<EventHandlers.GenericHandler>();
listenerCache.set(event, listeners);
}
delegateListeners.forEach(d => (listeners as Set<any>).add(d));
});
});
for(const listener of delegateListeners) {
(listeners as Set<any>).add(listener);
}
}
}
this._cachedGetListersValue = listenerCache;
}
return this._cachedGetListersValue;
Expand All @@ -550,11 +552,11 @@ export class Bus<TEventMap extends Events.EventMap = Events.EventMap> implements
public get ownListeners(): ReadonlyMap<EventKeys<TEventMap>|Events.WILDCARD, ReadonlySet<EventHandlers.EventHandler<TEventMap, any>>> {
if(!this._cachedGetOwnListenersValue) {
const ownListenerCache = new Map<EventKeys<TEventMap>|Events.WILDCARD, Set<EventHandlers.EventHandler<TEventMap, any>>>();
this.bus.forEach((listeners, event) => {
for(const [event, listeners] of this.bus) {
if(listeners.size) {
ownListenerCache.set(event, new Set(listeners));
}
});
}
this._cachedGetOwnListenersValue = ownListenerCache;
}
return this._cachedGetOwnListenersValue;
Expand Down Expand Up @@ -610,7 +612,11 @@ export class Bus<TEventMap extends Events.EventMap = Events.EventMap> implements
}

private releaseDelegates(): void {
this._delegates.forEach(subs => over(subs)());
for(const subs of Object.values(this._delegates)) {
for(const sub of subs()) {
sub();
}
}
this._delegates.clear();
}

Expand Down Expand Up @@ -675,13 +681,19 @@ export class Bus<TEventMap extends Events.EventMap = Events.EventMap> implements
private emitEvent(event: EventKeys<TEventMap>|Events.WILDCARD, ...args: any[]): boolean {
const handlers = this.bus.get(event);
if(handlers && handlers.size) {
handlers.forEach(async fn => {
for(const fn of handlers) {
try {
await fn(...args);
const execution = fn(...args);

// Emit errors if fn returns promise that rejects
(execution as Promise<any>)?.catch?.((e) => {
this.emitLifecycleEvent(Lifecycle.error, {error: e, event});
});
} catch(e) {
// Emit errors if callback fails synchronously
this.emitLifecycleEvent(Lifecycle.error, {error: e, event});
}
});
}
return true;
}
return false;
Expand All @@ -690,10 +702,26 @@ export class Bus<TEventMap extends Events.EventMap = Events.EventMap> implements
private emitLifecycleEvent<L extends Lifecycle>(event: L, payload: Lifecycle.EventMap<TEventMap>[L]): void {
const handlers = this.lifecycle.get(event);
if(handlers && handlers.size) {
handlers.forEach(async fn => {
for(const fn of handlers) {
try {
await fn(payload);
const execution = fn(payload);

// Emit errors if fn returns promise that rejects
(execution as Promise<any>)?.catch?.((e) => {
if(event === Lifecycle.error) {
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The only thing I don't like about this PR is the redundancy here. Lines 709-717 are the same as 724-734.

I thought about pulling this error logic into a function to eliminate the redundancy, but I wanted to avoid the overhead of creating a closure when we hit the happy path.

const errorPayload = payload as Lifecycle.EventMap<TEventMap>['error'];
this.options.logger.error('Error thrown in async error handler', {
errorHandler: fn.name,
errorHandlerError: e,
originalEvent: errorPayload.event,
eventHandlerError: errorPayload.error
});
} else {
this.emitLifecycleEvent(Lifecycle.error, {error: e, event});
}
})
} catch(e) {
// Emit errors if callback fails synchronously
if(event === Lifecycle.error) {
const errorPayload = payload as Lifecycle.EventMap<TEventMap>['error'];
this.options.logger.error('Error thrown in error handler', {
Expand All @@ -706,7 +734,7 @@ export class Bus<TEventMap extends Events.EventMap = Events.EventMap> implements
this.emitLifecycleEvent(Lifecycle.error, {error: e, event});
}
}
});
}
}
}

Expand Down
62 changes: 54 additions & 8 deletions src/strongbus_spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -786,15 +786,61 @@ describe('Strongbus.Bus', () => {
sub2();
});

it('raises "error" when errors are thrown in the listener', () => {
const error = new Error('Error in callback');
bus.on('bar', () => {
throw error;
describe('error events', () => {
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All these new specs are just capturing existing behavior. They all pass against the master branch.

it('emits "error" when errors are thrown in the listener', () => {
const error = new Error('Error in callback');
bus.on('bar', () => {
throw error;
});
bus.emit('bar', true);
expect(onError).toHaveBeenCalledWith({
error,
event: 'bar'
});
});
bus.emit('bar', true);
expect(onError).toHaveBeenCalledWith({
error,
event: 'bar'

it('emits "error" when the listener returns a promise that rejects', async () => {
const error = new Error('Error in callback');
bus.on('bar', () => (
Promise.reject(error)
));
bus.emit('bar', true);

// Wait for promises to be processed
await Promise.resolve();

expect(onError).toHaveBeenCalledWith({
error,
event: 'bar'
});
});

it('emits an "error" event if a synchronous error is thrown in a hook', () => {
const error = new Error('error');
bus.hook('active', () => {
throw error;
});
bus.on('foo', () => {});
expect(onError).toHaveBeenCalledWith({
error,
event: 'active'
});
});

it('emits "error" when a hook returns a promise that rejects', async () => {
const error = new Error('error');
bus.hook('active', () => (
Promise.reject(error)
));
bus.on('foo', () => {});

// Wait for promises to be processed
await Promise.resolve();

expect(onError).toHaveBeenCalledWith({
error,
event: 'active'
});
});
});

Expand Down