Skip to content

Commit

Permalink
perf: don't add unload event listener (#18082)
Browse files Browse the repository at this point in the history
This commit changes how "unload" event is handled - before
this commit an event listener was added unconditionally in
the runtime bootstrapping function, which for some reason was
very expensive (0.3ms). Instead of adding an event listener,
a check was added to "dispatchEvent" function that performs
the same action (so it's only called if there's an event dispatched).
  • Loading branch information
bartlomieju authored Mar 9, 2023
1 parent 25d98ca commit 0f9df73
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 11 deletions.
9 changes: 9 additions & 0 deletions ext/web/02_event.js
Original file line number Diff line number Diff line change
Expand Up @@ -1056,6 +1056,15 @@ class EventTarget {
prefix: "Failed to execute 'dispatchEvent' on 'EventTarget'",
});

// This is an optimization to avoid creating an event listener
// on each startup.
// Stores the flag for checking whether unload is dispatched or not.
// This prevents the recursive dispatches of unload events.
// See https://github.com/denoland/deno/issues/9201.
if (event.type === "unload" && self === globalThis_) {
globalThis_[SymbolFor("isUnloadDispatched")] = true;
}

const { listeners } = self[eventTargetData];
if (!ReflectHas(listeners, event.type)) {
setTarget(event, this);
Expand Down
11 changes: 0 additions & 11 deletions runtime/js/99_main.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,6 @@ const {
ObjectSetPrototypeOf,
PromiseResolve,
Symbol,
SymbolFor,
SymbolIterator,
PromisePrototypeThen,
SafeWeakMap,
Expand Down Expand Up @@ -404,7 +403,6 @@ function bootstrapMainRuntime(runtimeOptions) {
if (hasBootstrapped) {
throw new Error("Worker runtime already bootstrapped");
}

performance.setTimeOrigin(DateNow());
globalThis_ = globalThis;

Expand Down Expand Up @@ -451,15 +449,6 @@ function bootstrapMainRuntime(runtimeOptions) {

core.setPromiseRejectCallback(promiseRejectCallback);

const isUnloadDispatched = SymbolFor("isUnloadDispatched");
// Stores the flag for checking whether unload is dispatched or not.
// This prevents the recursive dispatches of unload events.
// See https://github.com/denoland/deno/issues/9201.
globalThis[isUnloadDispatched] = false;
globalThis.addEventListener("unload", () => {
globalThis_[isUnloadDispatched] = true;
});

runtimeStart(runtimeOptions);

setNumCpus(runtimeOptions.cpuCount);
Expand Down

0 comments on commit 0f9df73

Please sign in to comment.