From 875952b226f893c42eaa91e7be2f45e9a807a517 Mon Sep 17 00:00:00 2001 From: James M Snell Date: Sun, 30 Jun 2024 00:43:27 -0700 Subject: [PATCH] lib: make navigator properties lazy 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. --- 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; } }