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>
This commit is contained in:
Matteo Collina authored and GitHub committed 2026-11-19 17:31:56 +00:00
1 parent 88b034fa75
commit f4fab9770b
8 files changed
+120 -27

No files matched your search

@@ -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);
}
+25 -4
View File
@@ -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;
}
+24 -4
View File
@@ -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;
+22 -5
View File
@@ -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;
+8 -5
View File
@@ -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);
}
/**
+5 -1
View File
@@ -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.
+1
View File
@@ -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) \
+18 -8
View File
@@ -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;