Skip to content

Commit b55ab01

Browse files
BridgeARrefack
authored andcommitted
lib: improve lazy requires
* internal/errors - assert should already be in place when calling any of the message generating functions. * No lazy load if not necessary. * Replace function calls with `if`s. PR-URL: nodejs#14167 Reviewed-By: Refael Ackermann <[email protected]> Reviewed-By: Timothy Gu <[email protected]>
1 parent 7bc666b commit b55ab01

File tree

7 files changed

+42
-93
lines changed

7 files changed

+42
-93
lines changed

lib/dgram.js

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@
2424
const assert = require('assert');
2525
const errors = require('internal/errors');
2626
const Buffer = require('buffer').Buffer;
27+
const dns = require('dns');
2728
const util = require('util');
2829
const EventEmitter = require('events');
2930
const setInitTriggerId = require('async_hooks').setInitTriggerId;
@@ -39,17 +40,13 @@ const BIND_STATE_UNBOUND = 0;
3940
const BIND_STATE_BINDING = 1;
4041
const BIND_STATE_BOUND = 2;
4142

42-
// lazily loaded
43+
// Lazily loaded
4344
var cluster = null;
44-
var dns = null;
4545

4646
const errnoException = util._errnoException;
4747
const exceptionWithHostPort = util._exceptionWithHostPort;
4848

4949
function lookup(address, family, callback) {
50-
if (!dns)
51-
dns = require('dns');
52-
5350
return dns.lookup(address, family, callback);
5451
}
5552

lib/internal/errors.js

Lines changed: 15 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -9,19 +9,9 @@
99
const kCode = Symbol('code');
1010
const messages = new Map();
1111

12-
var util;
13-
function lazyUtil() {
14-
if (!util)
15-
util = require('util');
16-
return util;
17-
}
18-
19-
var assert;
20-
function lazyAssert() {
21-
if (!assert)
22-
assert = require('assert');
23-
return assert;
24-
}
12+
// Lazily loaded
13+
var assert = null;
14+
var util = null;
2515

2616
function makeNodeError(Base) {
2717
return class NodeError extends Base {
@@ -45,13 +35,14 @@ class AssertionError extends Error {
4535
if (typeof options !== 'object' || options === null) {
4636
throw new exports.TypeError('ERR_INVALID_ARG_TYPE', 'options', 'object');
4737
}
48-
const util = lazyUtil();
49-
const message = options.message ||
50-
`${util.inspect(options.actual).slice(0, 128)} ` +
51-
`${options.operator} ` +
52-
util.inspect(options.expected).slice(0, 128);
38+
if (options.message) {
39+
super(options.message);
40+
} else {
41+
if (util === null) util = require('util');
42+
super(`${util.inspect(options.actual).slice(0, 128)} ` +
43+
`${options.operator} ${util.inspect(options.expected).slice(0, 128)}`);
44+
}
5345

54-
super(message);
5546
this.generatedMessage = !options.message;
5647
this.name = 'AssertionError [ERR_ASSERTION]';
5748
this.code = 'ERR_ASSERTION';
@@ -63,15 +54,16 @@ class AssertionError extends Error {
6354
}
6455

6556
function message(key, args) {
66-
const assert = lazyAssert();
57+
if (assert === null) assert = require('assert');
6758
assert.strictEqual(typeof key, 'string');
68-
const util = lazyUtil();
6959
const msg = messages.get(key);
7060
assert(msg, `An invalid error message key was used: ${key}.`);
71-
let fmt = util.format;
61+
let fmt;
7262
if (typeof msg === 'function') {
7363
fmt = msg;
7464
} else {
65+
if (util === null) util = require('util');
66+
fmt = util.format;
7567
if (args === undefined || args.length === 0)
7668
return msg;
7769
args.unshift(msg);
@@ -123,7 +115,6 @@ E('ERR_INDEX_OUT_OF_RANGE', 'Index out of range');
123115
E('ERR_INVALID_ARG_TYPE', invalidArgType);
124116
E('ERR_INVALID_ARRAY_LENGTH',
125117
(name, length, actual) => {
126-
const assert = lazyAssert();
127118
assert.strictEqual(typeof actual, 'number');
128119
return `The "${name}" array must have a length of ${
129120
length}. Received length ${actual}`;
@@ -152,10 +143,7 @@ E('ERR_INVALID_THIS', 'Value of "this" must be of type %s');
152143
E('ERR_INVALID_TUPLE', '%s must be an iterable %s tuple');
153144
E('ERR_INVALID_URL', 'Invalid URL: %s');
154145
E('ERR_INVALID_URL_SCHEME',
155-
(expected) => {
156-
lazyAssert();
157-
return `The URL must be ${oneOf(expected, 'scheme')}`;
158-
});
146+
(expected) => `The URL must be ${oneOf(expected, 'scheme')}`);
159147
E('ERR_IPC_CHANNEL_CLOSED', 'Channel closed');
160148
E('ERR_IPC_DISCONNECTED', 'IPC channel is already disconnected');
161149
E('ERR_IPC_ONE_PIPE', 'Child process can have only one IPC pipe');
@@ -191,7 +179,6 @@ E('ERR_V8BREAKITERATOR', 'Full ICU data not installed. ' +
191179
// Add new errors from here...
192180

193181
function invalidArgType(name, expected, actual) {
194-
const assert = lazyAssert();
195182
assert(name, 'name is required');
196183

197184
// determiner: 'must be' or 'must not be'
@@ -223,7 +210,6 @@ function invalidArgType(name, expected, actual) {
223210
}
224211

225212
function missingArgs(...args) {
226-
const assert = lazyAssert();
227213
assert(args.length > 0, 'At least one arg needs to be specified');
228214
let msg = 'The ';
229215
const len = args.length;

lib/internal/process.js

Lines changed: 5 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,7 @@
11
'use strict';
22

33
const errors = require('internal/errors');
4-
var _lazyConstants = null;
5-
6-
function lazyConstants() {
7-
if (!_lazyConstants) {
8-
_lazyConstants = process.binding('constants').os.signals;
9-
}
10-
return _lazyConstants;
11-
}
4+
const constants = process.binding('constants').os.signals;
125

136
const assert = process.assert = function(x, msg) {
147
if (!x) throw new errors.Error('ERR_ASSERTION', msg || 'assertion error');
@@ -178,8 +171,8 @@ function setupKillAndExit() {
178171
err = process._kill(pid, 0);
179172
} else {
180173
sig = sig || 'SIGTERM';
181-
if (lazyConstants()[sig]) {
182-
err = process._kill(pid, lazyConstants()[sig]);
174+
if (constants[sig]) {
175+
err = process._kill(pid, constants[sig]);
183176
} else {
184177
throw new errors.TypeError('ERR_UNKNOWN_SIGNAL', sig);
185178
}
@@ -201,7 +194,7 @@ function setupSignalHandlers() {
201194
const signalWraps = {};
202195

203196
function isSignal(event) {
204-
return typeof event === 'string' && lazyConstants()[event] !== undefined;
197+
return typeof event === 'string' && constants[event] !== undefined;
205198
}
206199

207200
// Detect presence of a listener for the special signal types
@@ -215,7 +208,7 @@ function setupSignalHandlers() {
215208

216209
wrap.onsignal = function() { process.emit(type); };
217210

218-
const signum = lazyConstants()[type];
211+
const signum = constants[type];
219212
const err = wrap.start(signum);
220213
if (err) {
221214
wrap.close();

lib/internal/process/stdio.js

Lines changed: 4 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,8 @@
11
'use strict';
22

3-
exports.setup = setupStdio;
4-
5-
var errors;
3+
const errors = require('internal/errors');
64

7-
function lazyErrors() {
8-
if (!errors)
9-
errors = require('internal/errors');
10-
return errors;
11-
}
5+
exports.setup = setupStdio;
126

137
function setupStdio() {
148
var stdin;
@@ -20,8 +14,7 @@ function setupStdio() {
2014
stdout = createWritableStdioStream(1);
2115
stdout.destroySoon = stdout.destroy;
2216
stdout._destroy = function(er, cb) {
23-
// avoid errors if we already emitted
24-
const errors = lazyErrors();
17+
// Avoid errors if we already emitted
2518
er = er || new errors.Error('ERR_STDOUT_CLOSE');
2619
cb(er);
2720
};
@@ -36,8 +29,7 @@ function setupStdio() {
3629
stderr = createWritableStdioStream(2);
3730
stderr.destroySoon = stderr.destroy;
3831
stderr._destroy = function(er, cb) {
39-
// avoid errors if we already emitted
40-
const errors = lazyErrors();
32+
// Avoid errors if we already emitted
4133
er = er || new errors.Error('ERR_STDERR_CLOSE');
4234
cb(er);
4335
};
@@ -95,7 +87,6 @@ function setupStdio() {
9587

9688
default:
9789
// Probably an error on in uv_guess_handle()
98-
const errors = lazyErrors();
9990
throw new errors.Error('ERR_UNKNOWN_STDIN_TYPE');
10091
}
10192

@@ -180,7 +171,6 @@ function createWritableStdioStream(fd) {
180171

181172
default:
182173
// Probably an error on in uv_guess_handle()
183-
const errors = lazyErrors();
184174
throw new errors.Error('ERR_UNKNOWN_STREAM_TYPE');
185175
}
186176

lib/internal/process/warning.js

Lines changed: 9 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -2,26 +2,16 @@
22

33
const config = process.binding('config');
44
const prefix = `(${process.release.name}:${process.pid}) `;
5+
const errors = require('internal/errors');
56

67
exports.setup = setupProcessWarnings;
78

8-
var errors;
9-
var fs;
109
var cachedFd;
1110
var acquiringFd = false;
1211
function nop() {}
1312

14-
function lazyErrors() {
15-
if (!errors)
16-
errors = require('internal/errors');
17-
return errors;
18-
}
19-
20-
function lazyFs() {
21-
if (!fs)
22-
fs = require('fs');
23-
return fs;
24-
}
13+
// Lazily loaded
14+
var fs = null;
2515

2616
function writeOut(message) {
2717
if (console && typeof console.error === 'function')
@@ -31,7 +21,8 @@ function writeOut(message) {
3121

3222
function onClose(fd) {
3323
return function() {
34-
lazyFs().close(fd, nop);
24+
if (fs === null) fs = require('fs');
25+
fs.close(fd, nop);
3526
};
3627
}
3728

@@ -53,14 +44,16 @@ function onAcquired(message) {
5344
return function(err, fd) {
5445
if (err)
5546
return writeOut(message);
56-
lazyFs().appendFile(fd, `${message}\n`, nop);
47+
if (fs === null) fs = require('fs');
48+
fs.appendFile(fd, `${message}\n`, nop);
5749
};
5850
}
5951

6052
function acquireFd(cb) {
6153
if (cachedFd === undefined && !acquiringFd) {
6254
acquiringFd = true;
63-
lazyFs().open(config.warningFile, 'a', onOpen(cb));
55+
if (fs === null) fs = require('fs');
56+
fs.open(config.warningFile, 'a', onOpen(cb));
6457
} else if (cachedFd !== undefined && !acquiringFd) {
6558
cb(null, cachedFd);
6659
} else {
@@ -112,7 +105,6 @@ function setupProcessWarnings() {
112105
// process.emitWarning(str[, type[, code]][, ctor])
113106
// process.emitWarning(str[, options])
114107
process.emitWarning = function(warning, type, code, ctor, now) {
115-
const errors = lazyErrors();
116108
var detail;
117109
if (type !== null && typeof type === 'object' && !Array.isArray(type)) {
118110
ctor = type.ctor;

lib/net.js

Lines changed: 5 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -43,9 +43,11 @@ const async_id_symbol = process.binding('async_wrap').async_id_symbol;
4343
const { newUid, setInitTriggerId } = require('async_hooks');
4444
const nextTick = require('internal/process/next_tick').nextTick;
4545
const errors = require('internal/errors');
46+
const dns = require('dns');
4647

47-
var cluster;
48-
var dns;
48+
// `cluster` is only used by `listenInCluster` so for startup performance
49+
// reasons it's lazy loaded.
50+
var cluster = null;
4951

5052
const errnoException = util._errnoException;
5153
const exceptionWithHostPort = util._exceptionWithHostPort;
@@ -999,7 +1001,6 @@ Socket.prototype.connect = function() {
9991001

10001002

10011003
function lookupAndConnect(self, options) {
1002-
const dns = lazyDns();
10031004
var host = options.host || 'localhost';
10041005
var port = options.port;
10051006
var localAddress = options.localAddress;
@@ -1347,18 +1348,11 @@ function emitListeningNT(self) {
13471348
}
13481349

13491350

1350-
function lazyDns() {
1351-
if (dns === undefined)
1352-
dns = require('dns');
1353-
return dns;
1354-
}
1355-
1356-
13571351
function listenInCluster(server, address, port, addressType,
13581352
backlog, fd, exclusive) {
13591353
exclusive = !!exclusive;
13601354

1361-
if (!cluster) cluster = require('cluster');
1355+
if (cluster === null) cluster = require('cluster');
13621356

13631357
if (cluster.isMaster || exclusive) {
13641358
// Will create a new handle
@@ -1484,7 +1478,6 @@ Server.prototype.listen = function() {
14841478
};
14851479

14861480
function lookupAndListen(self, port, address, backlog, exclusive) {
1487-
const dns = lazyDns();
14881481
dns.lookup(address, function doListen(err, ip, addressType) {
14891482
if (err) {
14901483
self.emit('error', err);

lib/readline.js

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -29,8 +29,9 @@
2929

3030
const errors = require('internal/errors');
3131
const { debug, inherits } = require('util');
32-
const Buffer = require('buffer').Buffer;
32+
const { Buffer } = require('buffer');
3333
const EventEmitter = require('events');
34+
const { StringDecoder } = require('string_decoder');
3435
const {
3536
CSI,
3637
emitKeys,
@@ -59,7 +60,6 @@ const ESCAPE_DECODER = Symbol('escape-decoder');
5960
// GNU readline library - keyseq-timeout is 500ms (default)
6061
const ESCAPE_CODE_TIMEOUT = 500;
6162

62-
6363
function createInterface(input, output, completer, terminal) {
6464
return new Interface(input, output, completer, terminal);
6565
}
@@ -181,7 +181,6 @@ function Interface(input, output, completer, terminal) {
181181
input.removeListener('data', ondata);
182182
input.removeListener('end', onend);
183183
});
184-
var StringDecoder = require('string_decoder').StringDecoder; // lazy load
185184
this._decoder = new StringDecoder('utf8');
186185

187186
} else {
@@ -989,7 +988,6 @@ Interface.prototype._ttyWrite = function(s, key) {
989988

990989
function emitKeypressEvents(stream, iface) {
991990
if (stream[KEYPRESS_DECODER]) return;
992-
var StringDecoder = require('string_decoder').StringDecoder; // lazy load
993991
stream[KEYPRESS_DECODER] = new StringDecoder('utf8');
994992

995993
stream[ESCAPE_DECODER] = emitKeys(stream);

0 commit comments

Comments
 (0)