Commit f4fab9770b0 for nodejs

commit f4fab9770b01c890a740a1ec318c8b2c77e0f7fc
Author: Matteo Collina <hello@matteocollina.com>
Date:   Thu Nov 19 18:31:56 2026 +0100

    module: avoid dictionary-mode objects on hot paths

    V8 keeps objects created from `{ __proto__: null }` literals, and from
    v8::Object::New() with names and values, in dictionary mode for their
    whole life. The module loader created such objects on every require()
    of a builtin and every import(), and kEmptyObject, the cached ESM
    resolve results and the requests from getModuleRequests() were all
    in dictionary mode as well.

    Use classes with a null-prototype prototype for the per-call objects,
    null the prototype of plain literals for the long-lived ones, and
    build module requests from a DictionaryTemplate.

    Signed-off-by: Matteo Collina <hello@matteocollina.com>
    PR-URL: https://github.com/nodejs/node/pull/67552
    Refs: https://adventures.nodeland.dev/archive/optimizing-objects-with-null-prototypes/
    Reviewed-By: Gürgün Dayıoğlu <hey@gurgun.day>
    Reviewed-By: Chengzhong Wu <legendecas@gmail.com>
    Reviewed-By: James M Snell <jasnell@gmail.com>

diff --git a/benchmark/module/module-require-builtin.js b/benchmark/module/module-require-builtin.js
new file mode 100644
index 00000000000..f68df90bb66
--- /dev/null
+++ b/benchmark/module/module-require-builtin.js
@@ -0,0 +1,17 @@
+'use strict';
+
+const common = require('../common.js');
+
+const bench = common.createBenchmark(main, {
+  prefix: ['', 'node:'],
+  n: [1e6],
+});
+
+function main({ prefix, n }) {
+  const ids = ['fs', 'path', 'util', 'events'].map((id) => `${prefix}${id}`);
+  bench.start();
+  for (let i = 0; i < n; i++) {
+    require(ids[i % ids.length]);
+  }
+  bench.end(n);
+}
diff --git a/lib/internal/modules/cjs/loader.js b/lib/internal/modules/cjs/loader.js
index f9c4a62f023..f7c08348f3d 100644
--- a/lib/internal/modules/cjs/loader.js
+++ b/lib/internal/modules/cjs/loader.js
@@ -1131,6 +1131,27 @@ function getExportsForCircularRequire(module) {
   return module.exports;
 }

+/**
+ * Result of resolving a module request for CommonJS loading. One is created on
+ * every require() that misses the relative resolve cache, e.g. every require()
+ * of a builtin. A `{ __proto__: null }` literal would be created in dictionary
+ * mode, so use a class with a null-prototype prototype to keep a fast map.
+ */
+class CJSResolveResult {
+  /**
+   * @param {string|undefined} url
+   * @param {string|undefined} format
+   * @param {string} filename
+   * @param {string|undefined} parentURL
+   */
+  constructor(url, format, filename, parentURL) {
+    this.url = url;
+    this.format = format;
+    this.filename = filename;
+    this.parentURL = parentURL;
+  }
+}
+ObjectSetPrototypeOf(CJSResolveResult.prototype, null);

 /**
  * Wraps result of Module._resolveFilename to include additional fields for hooks.
@@ -1139,11 +1160,11 @@ function getExportsForCircularRequire(module) {
  * @param {Module|undefined} parent
  * @param {boolean} isMain
  * @param {ResolveFilenameOptions} options
- * @returns {{url?: string, format?: string, parentURL?: string, filename: string}}
+ * @returns {CJSResolveResult}
  */
 function wrapResolveFilename(specifier, parent, isMain, options) {
   const filename = Module._resolveFilename(specifier, parent, isMain, options).toString();
-  return { __proto__: null, url: undefined, format: undefined, filename };
+  return new CJSResolveResult(undefined, undefined, filename, undefined);
 }

 /**
@@ -1164,7 +1185,7 @@ function defaultResolveImplForCJSLoading(specifier, parent, isMain, options) {
     if (!normalized) {
       throw new ERR_UNKNOWN_BUILTIN_MODULE(specifier);
     }
-    return { __proto__: null, url: specifier, format: 'builtin', filename: normalized };
+    return new CJSResolveResult(specifier, 'builtin', normalized, undefined);
   }
   return wrapResolveFilename(specifier, parent, isMain, options);
 }
@@ -1241,7 +1262,7 @@ function resolveForCJSWithHooks(specifier, parent, isMain, internalOptions) {
   const { url, format } = resolveResult;
   // Convert the URL from the hook chain back to a filename for internal use.
   const filename = convertURLToCJSFilename(url);
-  const result = { __proto__: null, url, format, filename, parentURL };
+  const result = new CJSResolveResult(url, format, filename, parentURL);
   debug('resolveForCJSWithHooks', specifier, parent?.id, isMain, shouldSkipModuleHooks, '->', result);
   return result;
 }
diff --git a/lib/internal/modules/esm/loader.js b/lib/internal/modules/esm/loader.js
index f8e68e7996c..80d6f875944 100644
--- a/lib/internal/modules/esm/loader.js
+++ b/lib/internal/modules/esm/loader.js
@@ -84,6 +84,26 @@ const { defaultLoadSync, throwUnknownModuleFormat } = require('internal/modules/
  * @typedef {import('../cjs/loader.js').Module} CJSModule
  */

+/**
+ * A module request created from JS, with the same fields as the requests returned by
+ * `ModuleWrap.prototype.getModuleRequests()`. `import()` creates one per call, and a
+ * `{ __proto__: null }` literal would be created in dictionary mode, so use a class
+ * with a null-prototype prototype to keep a fast map.
+ */
+class ImportRequest {
+  /**
+   * @param {string} specifier
+   * @param {number} phase
+   * @param {Record<string, string>} attributes
+   */
+  constructor(specifier, phase, attributes) {
+    this.specifier = specifier;
+    this.attributes = attributes;
+    this.phase = phase;
+  }
+}
+ObjectSetPrototypeOf(ImportRequest.prototype, null);
+
 /**
  * @typedef {Record<string, any>} ModuleExports
  */
@@ -501,7 +521,7 @@ class ModuleLoader {
    */
   async import(specifier, parentURL, importAttributes, phase = kEvaluationPhase, isEntryPoint = false) {
     return onImport.tracePromise(async () => {
-      const request = { specifier, phase, attributes: importAttributes, __proto__: null };
+      const request = new ImportRequest(specifier, phase, importAttributes);
       const moduleJob = this.getOrCreateModuleJob(parentURL, request);
       // Loading and linking are synchronous, but import() must still never evaluate the
       // module before returning to its caller, so yield once before running the job.
@@ -564,12 +584,12 @@ class ModuleLoader {
   resolveSync(parentURL, request) {
     const specifier = `${request.specifier}`;
     const importAttributes = request.attributes ?? kEmptyObject;
-    // Use an output parameter to track the state and avoid polluting the user-visible resolve results.
-    const out = { isResolvedByDefaultResolve: false, __proto__: null };

     let result;
     let isResolvedBySyncHooks = false;
     if (syncResolveHooks.length) {
+      // Use an output parameter to track the state and avoid polluting the user-visible resolve results.
+      const out = { isResolvedByDefaultResolve: false, __proto__: null };
       // Has module.registerHooks() hooks, chain the default resolver in the default step.
       result = resolveWithSyncHooks(specifier, parentURL, importAttributes, this.#defaultConditions,
                                     this.#defaultResolve.bind(this, out));
@@ -583,7 +603,7 @@ class ModuleLoader {
         importAttributes,
         __proto__: null,
       };
-      result = this.#defaultResolve(out, specifier, context);
+      result = this.#cachedDefaultResolve(specifier, context);
     }
     result.isResolvedBySyncHooks = isResolvedBySyncHooks;
     return result;
diff --git a/lib/internal/modules/esm/module_job.js b/lib/internal/modules/esm/module_job.js
index ba300785c9e..6c98644a732 100644
--- a/lib/internal/modules/esm/module_job.js
+++ b/lib/internal/modules/esm/module_job.js
@@ -277,6 +277,23 @@ const handleCJSNamedExportError = (error, module, commonJsDeps) => {
   }
 };

+/**
+ * Result of evaluating a module job. `import()` gets one on every call, and a
+ * `{ __proto__: null }` literal would be created in dictionary mode, so use a class
+ * with a null-prototype prototype to keep a fast map.
+ */
+class ModuleJobResult {
+  /**
+   * @param {ModuleWrap} module
+   * @param {object|undefined} namespace
+   */
+  constructor(module, namespace) {
+    this.module = module;
+    this.namespace = namespace;
+  }
+}
+ObjectSetPrototypeOf(ModuleJobResult.prototype, null);
+
 class ModuleJobBase {
   constructor(loader, url, importAttributes, phase, isMain, inspectBrk) {
     assert(typeof phase === 'number');
@@ -449,7 +466,7 @@ class ModuleJob extends ModuleJobBase {
       explainCommonJSGlobalLikeNotDefinedError(e, this.module.url, this.module.hasTopLevelAwait);
       throw e;
     }
-    return { __proto__: null, module: this.module };
+    return new ModuleJobResult(this.module, undefined);
   }
 }

@@ -513,7 +530,7 @@ class ModuleJobSync extends ModuleJobBase {
       if (this.evaluationPromise) {
         await this.evaluationPromise;
       }
-      return { __proto__: null, module: this.module };
+      return new ModuleJobResult(this.module, undefined);
     }
     if (status < kInstantiated) {
       // Either a fresh module - links were already resolved synchronously in the constructor -
@@ -540,7 +557,7 @@ class ModuleJobSync extends ModuleJobBase {
       }
       await this.evaluationPromise;
       this.evaluationPromise = undefined;
-      return { __proto__: null, module: this.module };
+      return new ModuleJobResult(this.module, undefined);
     }
     // No top-level `await`: evaluate synchronously
     try {
@@ -549,7 +566,7 @@ class ModuleJobSync extends ModuleJobBase {
       explainCommonJSGlobalLikeNotDefinedError(evaluateError, this.module.url, this.module.hasTopLevelAwait);
       throw evaluateError;
     }
-    return { __proto__: null, module: this.module };
+    return new ModuleJobResult(this.module, undefined);
   }

   // Evaluate this module synchronously, pausing at the first line of user land JS
@@ -572,7 +589,7 @@ class ModuleJobSync extends ModuleJobBase {
     setHasStartedUserESMExecution();
     try {
       const namespace = this.#evaluateSync();
-      return { __proto__: null, module: this.module, namespace };
+      return new ModuleJobResult(this.module, namespace);
     } catch (e) {
       explainCommonJSGlobalLikeNotDefinedError(e, this.module.url, this.module.hasTopLevelAwait);
       throw e;
diff --git a/lib/internal/modules/esm/resolve.js b/lib/internal/modules/esm/resolve.js
index 10c6cf3178d..dd96321093a 100644
--- a/lib/internal/modules/esm/resolve.js
+++ b/lib/internal/modules/esm/resolve.js
@@ -7,6 +7,7 @@ const {
   JSONStringify,
   ObjectGetOwnPropertyNames,
   ObjectPrototypeHasOwnProperty,
+  ObjectSetPrototypeOf,
   RegExpPrototypeExec,
   RegExpPrototypeSymbolReplace,
   String,
@@ -860,12 +861,12 @@ function defaultResolve(specifier, context = kEmptyObject) {
     protocol = parsed.protocol;

     if (protocol === 'data:') {
-      return { __proto__: null, url: parsed.href };
+      return ObjectSetPrototypeOf({ url: parsed.href }, null);
     }
   }

   protocol ??= parsed?.protocol;
-  if (protocol === 'node:') { return { __proto__: null, url: specifier }; }
+  if (protocol === 'node:') { return ObjectSetPrototypeOf({ url: specifier }, null); }


   const isMain = parentURL === undefined;
@@ -903,13 +904,15 @@ function defaultResolve(specifier, context = kEmptyObject) {
     throw error;
   }

-  return {
-    __proto__: null,
+  // The result is cached by the loader and read on every later resolution of the same
+  // request, so null the prototype of a plain literal instead of using a
+  // `{ __proto__: null }` literal, which V8 would keep in dictionary mode.
+  return ObjectSetPrototypeOf({
     // Do NOT cast `url` to a string: that will work even when there are real
     // problems, silencing them
     url: url.href,
     format: defaultGetFormatWithoutErrors(url, context),
-  };
+  }, null);
 }

 /**
diff --git a/lib/internal/util.js b/lib/internal/util.js
index 2f72e636ab9..81aa9f6f45d 100644
--- a/lib/internal/util.js
+++ b/lib/internal/util.js
@@ -700,7 +700,11 @@ const kEnumerableProperty = ObjectFreeze({
   enumerable: true,
 });

-const kEmptyObject = ObjectFreeze({ __proto__: null });
+// A `{ __proto__: null }` literal always starts in dictionary mode in V8 and
+// stays there, which makes every property lookup on it (e.g. reading an option
+// off the default `options = kEmptyObject`) a hash table probe. Null the
+// prototype of a plain literal instead so the object keeps a fast map.
+const kEmptyObject = ObjectFreeze(ObjectSetPrototypeOf({}, null));

 /**
  * Mimics `obj[key] = value` but ignoring potential prototype inheritance.
diff --git a/src/env_properties.h b/src/env_properties.h
index 3c52ea87498..2f3d814ff49 100644
--- a/src/env_properties.h
+++ b/src/env_properties.h
@@ -442,6 +442,7 @@
   V(lock_query_template, v8::DictionaryTemplate)                               \
   V(message_port_constructor_template, v8::FunctionTemplate)                   \
   V(module_wrap_constructor_template, v8::FunctionTemplate)                    \
+  V(module_request_template, v8::DictionaryTemplate)                           \
   V(mx_record_template, v8::DictionaryTemplate)                                \
   V(naptr_record_template, v8::DictionaryTemplate)                             \
   V(object_stats_template, v8::DictionaryTemplate)                             \
diff --git a/src/module_wrap.cc b/src/module_wrap.cc
index be3e6f668c0..c680a85e8e0 100644
--- a/src/module_wrap.cc
+++ b/src/module_wrap.cc
@@ -28,6 +28,7 @@ using v8::ArrayBufferView;
 using v8::Boolean;
 using v8::Context;
 using v8::Data;
+using v8::DictionaryTemplate;
 using v8::EscapableHandleScope;
 using v8::Exception;
 using v8::FixedArray;
@@ -598,6 +599,21 @@ static Local<Array> createModuleRequestsContainer(
   Local<Context> context = realm->context();
   LocalVector<Value> requests(isolate, raw_requests->Length());

+  // v8::Object::New() with names and values always creates the object in
+  // dictionary mode. Use a DictionaryTemplate instead so that the requests,
+  // which the loader reads for every import while linking, get a fast map.
+  Environment* env = realm->env();
+  Local<DictionaryTemplate> tmpl = env->module_request_template();
+  if (tmpl.IsEmpty()) {
+    static constexpr std::string_view names[] = {
+        "specifier",
+        "attributes",
+        "phase",
+    };
+    tmpl = DictionaryTemplate::New(isolate, names);
+    env->set_module_request_template(tmpl);
+  }
+
   for (int i = 0; i < raw_requests->Length(); i++) {
     DCHECK(raw_requests->Get(i)->IsModuleRequest());
     Local<ModuleRequest> module_request =
@@ -612,20 +628,14 @@ static Local<Array> createModuleRequestsContainer(
         createImportAttributesContainer(realm, isolate, raw_attributes, 3);
     ModuleImportPhase phase = module_request->GetPhase();

-    Local<Name> names[] = {
-        realm->isolate_data()->specifier_string(),
-        realm->isolate_data()->attributes_string(),
-        realm->isolate_data()->phase_string(),
-    };
-    Local<Value> values[] = {
+    MaybeLocal<Value> values[] = {
         specifier,
         attributes,
         Integer::New(isolate, to_phase_constant(phase)),
     };
-    DCHECK_EQ(arraysize(names), arraysize(values));

     Local<Object> request =
-        Object::New(isolate, Null(isolate), names, values, arraysize(names));
+        NewDictionaryInstanceNullProto(context, tmpl, values).ToLocalChecked();
     request->SetIntegrityLevel(context, v8::IntegrityLevel::kFrozen).Check();

     requests[i] = request;