From f9b43044efc65030ed69c3d2c89fd775c7f07d94 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bartek=20Iwa=C5=84czuk?= Date: Wed, 8 Mar 2023 21:08:54 -0400 Subject: [PATCH] perf: don't add unload event listener (#18082) 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). --- ext/web/02_event.js | 9 +++++++++ runtime/js/99_main.js | 11 ----------- 2 files changed, 9 insertions(+), 11 deletions(-) diff --git a/ext/web/02_event.js b/ext/web/02_event.js index 40731af4ce579e..dd8b4f57b9d94a 100644 --- a/ext/web/02_event.js +++ b/ext/web/02_event.js @@ -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); diff --git a/runtime/js/99_main.js b/runtime/js/99_main.js index e3e7e64d827d37..d043f485e2b803 100644 --- a/runtime/js/99_main.js +++ b/runtime/js/99_main.js @@ -30,7 +30,6 @@ const { ObjectSetPrototypeOf, PromiseResolve, Symbol, - SymbolFor, SymbolIterator, PromisePrototypeThen, SafeWeakMap, @@ -404,7 +403,6 @@ function bootstrapMainRuntime(runtimeOptions) { if (hasBootstrapped) { throw new Error("Worker runtime already bootstrapped"); } - performance.setTimeOrigin(DateNow()); globalThis_ = globalThis; @@ -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);