From 1f6fcd66feb76097d4b557fee49cd8cf68da1669 Mon Sep 17 00:00:00 2001 From: James M Snell Date: Thu, 4 Jul 2024 07:35:28 -0700 Subject: [PATCH] lib: make navigator properties lazy MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Noticed in some benchmarking/profiling that the Navigator object constructor was rather expensive and slow due to initialization of properties during construction. It makes more sense for these to be lazily initialized on first access. PR-URL: https://github.com/nodejs/node/pull/53649 Reviewed-By: Moshe Atlow Reviewed-By: Filip Skokan Reviewed-By: Matteo Collina Reviewed-By: Tobias Nießen Reviewed-By: Yagiz Nizipli Reviewed-By: Benjamin Gruenbaum --- lib/internal/navigator.js | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/lib/internal/navigator.js b/lib/internal/navigator.js index 546505e9460103..e56b2da5e339e3 100644 --- a/lib/internal/navigator.js +++ b/lib/internal/navigator.js @@ -78,10 +78,10 @@ function getNavigatorPlatform(process) { class Navigator { // Private properties are used to avoid brand validations. #availableParallelism; - #userAgent = `Node.js/${StringPrototypeSlice(nodeVersion, 1, StringPrototypeIndexOf(nodeVersion, '.'))}`; - #platform = getNavigatorPlatform(process); - #language = Intl?.Collator().resolvedOptions().locale || 'en-US'; - #languages = ObjectFreeze([this.#language]); + #userAgent; + #platform; + #language; + #languages; constructor() { if (arguments[0] === kInitialize) { @@ -102,6 +102,7 @@ class Navigator { * @return {string} */ get language() { + this.#language ??= Intl?.Collator().resolvedOptions().locale || 'en-US'; return this.#language; } @@ -109,6 +110,7 @@ class Navigator { * @return {Array} */ get languages() { + this.#languages ??= ObjectFreeze([this.language]); return this.#languages; } @@ -116,6 +118,7 @@ class Navigator { * @return {string} */ get userAgent() { + this.#userAgent ??= `Node.js/${StringPrototypeSlice(nodeVersion, 1, StringPrototypeIndexOf(nodeVersion, '.'))}`; return this.#userAgent; } @@ -123,6 +126,7 @@ class Navigator { * @return {string} */ get platform() { + this.#platform ??= getNavigatorPlatform(process); return this.#platform; } }