Skip to content

Commit 3fd2893

Browse files
mcollinaaduh95
authored andcommitted
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: #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>
1 parent ac7c1ac commit 3fd2893

8 files changed

Lines changed: 120 additions & 27 deletions

File tree

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
'use strict';
2+
3+
const common = require('../common.js');
4+
5+
const bench = common.createBenchmark(main, {
6+
prefix: ['', 'node:'],
7+
n: [1e6],
8+
});
9+
10+
function main({ prefix, n }) {
11+
const ids = ['fs', 'path', 'util', 'events'].map((id) => `${prefix}${id}`);
12+
bench.start();
13+
for (let i = 0; i < n; i++) {
14+
require(ids[i % ids.length]);
15+
}
16+
bench.end(n);
17+
}

‎lib/internal/modules/cjs/loader.js‎

Lines changed: 25 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1131,6 +1131,27 @@ function getExportsForCircularRequire(module) {
11311131
return module.exports;
11321132
}
11331133

1134+
/**
1135+
* Result of resolving a module request for CommonJS loading. One is created on
1136+
* every require() that misses the relative resolve cache, e.g. every require()
1137+
* of a builtin. A `{ __proto__: null }` literal would be created in dictionary
1138+
* mode, so use a class with a null-prototype prototype to keep a fast map.
1139+
*/
1140+
class CJSResolveResult {
1141+
/**
1142+
* @param {string|undefined} url
1143+
* @param {string|undefined} format
1144+
* @param {string} filename
1145+
* @param {string|undefined} parentURL
1146+
*/
1147+
constructor(url, format, filename, parentURL) {
1148+
this.url = url;
1149+
this.format = format;
1150+
this.filename = filename;
1151+
this.parentURL = parentURL;
1152+
}
1153+
}
1154+
ObjectSetPrototypeOf(CJSResolveResult.prototype, null);
11341155

11351156
/**
11361157
* Wraps result of Module._resolveFilename to include additional fields for hooks.
@@ -1139,11 +1160,11 @@ function getExportsForCircularRequire(module) {
11391160
* @param {Module|undefined} parent
11401161
* @param {boolean} isMain
11411162
* @param {ResolveFilenameOptions} options
1142-
* @returns {{url?: string, format?: string, parentURL?: string, filename: string}}
1163+
* @returns {CJSResolveResult}
11431164
*/
11441165
function wrapResolveFilename(specifier, parent, isMain, options) {
11451166
const filename = Module._resolveFilename(specifier, parent, isMain, options).toString();
1146-
return { __proto__: null, url: undefined, format: undefined, filename };
1167+
return new CJSResolveResult(undefined, undefined, filename, undefined);
11471168
}
11481169

11491170
/**
@@ -1164,7 +1185,7 @@ function defaultResolveImplForCJSLoading(specifier, parent, isMain, options) {
11641185
if (!normalized) {
11651186
throw new ERR_UNKNOWN_BUILTIN_MODULE(specifier);
11661187
}
1167-
return { __proto__: null, url: specifier, format: 'builtin', filename: normalized };
1188+
return new CJSResolveResult(specifier, 'builtin', normalized, undefined);
11681189
}
11691190
return wrapResolveFilename(specifier, parent, isMain, options);
11701191
}
@@ -1241,7 +1262,7 @@ function resolveForCJSWithHooks(specifier, parent, isMain, internalOptions) {
12411262
const { url, format } = resolveResult;
12421263
// Convert the URL from the hook chain back to a filename for internal use.
12431264
const filename = convertURLToCJSFilename(url);
1244-
const result = { __proto__: null, url, format, filename, parentURL };
1265+
const result = new CJSResolveResult(url, format, filename, parentURL);
12451266
debug('resolveForCJSWithHooks', specifier, parent?.id, isMain, shouldSkipModuleHooks, '->', result);
12461267
return result;
12471268
}

‎lib/internal/modules/esm/loader.js‎

Lines changed: 24 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,26 @@ const { defaultLoadSync, throwUnknownModuleFormat } = require('internal/modules/
8484
* @typedef {import('../cjs/loader.js').Module} CJSModule
8585
*/
8686

87+
/**
88+
* A module request created from JS, with the same fields as the requests returned by
89+
* `ModuleWrap.prototype.getModuleRequests()`. `import()` creates one per call, and a
90+
* `{ __proto__: null }` literal would be created in dictionary mode, so use a class
91+
* with a null-prototype prototype to keep a fast map.
92+
*/
93+
class ImportRequest {
94+
/**
95+
* @param {string} specifier
96+
* @param {number} phase
97+
* @param {Record<string, string>} attributes
98+
*/
99+
constructor(specifier, phase, attributes) {
100+
this.specifier = specifier;
101+
this.attributes = attributes;
102+
this.phase = phase;
103+
}
104+
}
105+
ObjectSetPrototypeOf(ImportRequest.prototype, null);
106+
87107
/**
88108
* @typedef {Record<string, any>} ModuleExports
89109
*/
@@ -501,7 +521,7 @@ class ModuleLoader {
501521
*/
502522
async import(specifier, parentURL, importAttributes, phase = kEvaluationPhase, isEntryPoint = false) {
503523
return onImport.tracePromise(async () => {
504-
const request = { specifier, phase, attributes: importAttributes, __proto__: null };
524+
const request = new ImportRequest(specifier, phase, importAttributes);
505525
const moduleJob = this.getOrCreateModuleJob(parentURL, request);
506526
// Loading and linking are synchronous, but import() must still never evaluate the
507527
// module before returning to its caller, so yield once before running the job.
@@ -564,12 +584,12 @@ class ModuleLoader {
564584
resolveSync(parentURL, request) {
565585
const specifier = `${request.specifier}`;
566586
const importAttributes = request.attributes ?? kEmptyObject;
567-
// Use an output parameter to track the state and avoid polluting the user-visible resolve results.
568-
const out = { isResolvedByDefaultResolve: false, __proto__: null };
569587

570588
let result;
571589
let isResolvedBySyncHooks = false;
572590
if (syncResolveHooks.length) {
591+
// Use an output parameter to track the state and avoid polluting the user-visible resolve results.
592+
const out = { isResolvedByDefaultResolve: false, __proto__: null };
573593
// Has module.registerHooks() hooks, chain the default resolver in the default step.
574594
result = resolveWithSyncHooks(specifier, parentURL, importAttributes, this.#defaultConditions,
575595
this.#defaultResolve.bind(this, out));
@@ -583,7 +603,7 @@ class ModuleLoader {
583603
importAttributes,
584604
__proto__: null,
585605
};
586-
result = this.#defaultResolve(out, specifier, context);
606+
result = this.#cachedDefaultResolve(specifier, context);
587607
}
588608
result.isResolvedBySyncHooks = isResolvedBySyncHooks;
589609
return result;

‎lib/internal/modules/esm/module_job.js‎

Lines changed: 22 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -277,6 +277,23 @@ const handleCJSNamedExportError = (error, module, commonJsDeps) => {
277277
}
278278
};
279279

280+
/**
281+
* Result of evaluating a module job. `import()` gets one on every call, and a
282+
* `{ __proto__: null }` literal would be created in dictionary mode, so use a class
283+
* with a null-prototype prototype to keep a fast map.
284+
*/
285+
class ModuleJobResult {
286+
/**
287+
* @param {ModuleWrap} module
288+
* @param {object|undefined} namespace
289+
*/
290+
constructor(module, namespace) {
291+
this.module = module;
292+
this.namespace = namespace;
293+
}
294+
}
295+
ObjectSetPrototypeOf(ModuleJobResult.prototype, null);
296+
280297
class ModuleJobBase {
281298
constructor(loader, url, importAttributes, phase, isMain, inspectBrk) {
282299
assert(typeof phase === 'number');
@@ -449,7 +466,7 @@ class ModuleJob extends ModuleJobBase {
449466
explainCommonJSGlobalLikeNotDefinedError(e, this.module.url, this.module.hasTopLevelAwait);
450467
throw e;
451468
}
452-
return { __proto__: null, module: this.module };
469+
return new ModuleJobResult(this.module, undefined);
453470
}
454471
}
455472

@@ -513,7 +530,7 @@ class ModuleJobSync extends ModuleJobBase {
513530
if (this.evaluationPromise) {
514531
await this.evaluationPromise;
515532
}
516-
return { __proto__: null, module: this.module };
533+
return new ModuleJobResult(this.module, undefined);
517534
}
518535
if (status < kInstantiated) {
519536
// Either a fresh module - links were already resolved synchronously in the constructor -
@@ -540,7 +557,7 @@ class ModuleJobSync extends ModuleJobBase {
540557
}
541558
await this.evaluationPromise;
542559
this.evaluationPromise = undefined;
543-
return { __proto__: null, module: this.module };
560+
return new ModuleJobResult(this.module, undefined);
544561
}
545562
// No top-level `await`: evaluate synchronously
546563
try {
@@ -549,7 +566,7 @@ class ModuleJobSync extends ModuleJobBase {
549566
explainCommonJSGlobalLikeNotDefinedError(evaluateError, this.module.url, this.module.hasTopLevelAwait);
550567
throw evaluateError;
551568
}
552-
return { __proto__: null, module: this.module };
569+
return new ModuleJobResult(this.module, undefined);
553570
}
554571

555572
// Evaluate this module synchronously, pausing at the first line of user land JS
@@ -572,7 +589,7 @@ class ModuleJobSync extends ModuleJobBase {
572589
setHasStartedUserESMExecution();
573590
try {
574591
const namespace = this.#evaluateSync();
575-
return { __proto__: null, module: this.module, namespace };
592+
return new ModuleJobResult(this.module, namespace);
576593
} catch (e) {
577594
explainCommonJSGlobalLikeNotDefinedError(e, this.module.url, this.module.hasTopLevelAwait);
578595
throw e;

‎lib/internal/modules/esm/resolve.js‎

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ const {
77
JSONStringify,
88
ObjectGetOwnPropertyNames,
99
ObjectPrototypeHasOwnProperty,
10+
ObjectSetPrototypeOf,
1011
RegExpPrototypeExec,
1112
RegExpPrototypeSymbolReplace,
1213
SafeSet,
@@ -946,12 +947,12 @@ function defaultResolve(specifier, context = kEmptyObject) {
946947
protocol = parsed.protocol;
947948

948949
if (protocol === 'data:') {
949-
return { __proto__: null, url: parsed.href };
950+
return ObjectSetPrototypeOf({ url: parsed.href }, null);
950951
}
951952
}
952953

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

956957

957958
const isMain = parentURL === undefined;
@@ -989,13 +990,15 @@ function defaultResolve(specifier, context = kEmptyObject) {
989990
throw error;
990991
}
991992

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

10011004
/**

‎lib/internal/util.js‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -700,7 +700,11 @@ const kEnumerableProperty = ObjectFreeze({
700700
enumerable: true,
701701
});
702702

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

705709
/**
706710
* Mimics `obj[key] = value` but ignoring potential prototype inheritance.

‎src/env_properties.h‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -442,6 +442,7 @@
442442
V(lock_query_template, v8::DictionaryTemplate) \
443443
V(message_port_constructor_template, v8::FunctionTemplate) \
444444
V(module_wrap_constructor_template, v8::FunctionTemplate) \
445+
V(module_request_template, v8::DictionaryTemplate) \
445446
V(mx_record_template, v8::DictionaryTemplate) \
446447
V(naptr_record_template, v8::DictionaryTemplate) \
447448
V(object_stats_template, v8::DictionaryTemplate) \

‎src/module_wrap.cc‎

Lines changed: 18 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@ using v8::ArrayBufferView;
2828
using v8::Boolean;
2929
using v8::Context;
3030
using v8::Data;
31+
using v8::DictionaryTemplate;
3132
using v8::EscapableHandleScope;
3233
using v8::Exception;
3334
using v8::FixedArray;
@@ -598,6 +599,21 @@ static Local<Array> createModuleRequestsContainer(
598599
Local<Context> context = realm->context();
599600
LocalVector<Value> requests(isolate, raw_requests->Length());
600601

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

615-
Local<Name> names[] = {
616-
realm->isolate_data()->specifier_string(),
617-
realm->isolate_data()->attributes_string(),
618-
realm->isolate_data()->phase_string(),
619-
};
620-
Local<Value> values[] = {
631+
MaybeLocal<Value> values[] = {
621632
specifier,
622633
attributes,
623634
Integer::New(isolate, to_phase_constant(phase)),
624635
};
625-
DCHECK_EQ(arraysize(names), arraysize(values));
626636

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

631641
requests[i] = request;

0 commit comments

Comments
 (0)