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

Restructured code to reduce the number of allocations during dispatch. #1

Merged
merged 1 commit into from
Oct 23, 2022
Merged
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
14 changes: 9 additions & 5 deletions EventListenerManager.js
Original file line number Diff line number Diff line change
Expand Up @@ -50,17 +50,20 @@ export default class EventListenerManager {
// We hope to process results synchronously if possibly,
// so this method must not be "async".
dispatchWithDetails(...args) {
const listeners = Array.from(this._listeners);
const results = listeners.map(listener => {
const results = Array(this._listeners.size);
let index = 0;

for (let listener of this._listeners) {
const startAt = EventListenerManager.debug && Date.now();
const timer = EventListenerManager.debug && setTimeout(() => {
const listenerAddedStack = this._stacksOnListenerAdded.get(listener);
console.log(`listener does not respond in ${TIMEOUT}ms.\n----------------------\n${listenerAddedStack || 'non debug mode or already removed listener:\n'+listener.toString()}\n----------------------\n${new Error().stack}\n----------------------\nargs:`, args);
}, TIMEOUT);

try {
const result = listener(...args);
if (result instanceof Promise)
return result
results[index++] = result
.catch(e => {
console.log(e);
})
Expand All @@ -76,7 +79,7 @@ export default class EventListenerManager {
});
if (timer)
clearTimeout(timer);
return {
results[index++] = {
value: result,
elapsed: EventListenerManager.debug && (Date.now() - startAt),
async: false,
Expand All @@ -88,7 +91,8 @@ export default class EventListenerManager {
if (timer)
clearTimeout(timer);
}
});
}

if (results.some(result => result instanceof Promise))
return Promise.all(results);
else
Expand Down