Skip to content

Commit

Permalink
lib: make navigator properties lazy
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
jasnell committed Jun 30, 2024
1 parent fe2d4dc commit 3d2e10f
Showing 1 changed file with 8 additions and 4 deletions.
12 changes: 8 additions & 4 deletions lib/internal/navigator.js
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand All @@ -102,27 +102,31 @@ class Navigator {
* @return {string}
*/
get language() {
this.#language ??= Intl?.Collator().resolvedOptions().locale || 'en-US';
return this.#language;
}

/**
* @return {Array<string>}
*/
get languages() {
this.#languages ??= ObjectFreeze([this.#language]);
return this.#languages;
}

/**
* @return {string}
*/
get userAgent() {
this.#userAgent ??= `Node.js/${StringPrototypeSlice(nodeVersion, 1, StringPrototypeIndexOf(nodeVersion, '.'))}`;
return this.#userAgent;
}

/**
* @return {string}
*/
get platform() {
this.#platform ??= getNavigatorPlatform(process);
return this.#platform;
}
}
Expand Down

0 comments on commit 3d2e10f

Please sign in to comment.