Skip to content

Commit cf1fe76

Browse files
BridgeARjasnell
authored andcommittedSep 21, 2017
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: #14167 Reviewed-By: Refael Ackermann <[email protected]> Reviewed-By: Timothy Gu <[email protected]>
1 parent f6c65e6 commit cf1fe76

File tree

7 files changed

+41
-88
lines changed

7 files changed

+41
-88
lines changed
 

‎lib/dgram.js

+2-5
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

+14-23
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);
@@ -240,7 +232,6 @@ E('ERR_VALID_PERFORMANCE_ENTRY_TYPE',
240232
// Add new errors from here...
241233

242234
function invalidArgType(name, expected, actual) {
243-
const assert = lazyAssert();
244235
assert(name, 'name is required');
245236
var msg = `The "${name}" argument must be ${oneOf(expected, 'type')}`;
246237
if (arguments.length >= 3) {

‎lib/internal/process.js

+5-13
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,7 @@
11
'use strict';
22

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

146
const assert = process.assert = function(x, msg) {
157
if (!x) throw new Error(msg || 'assertion error');
@@ -177,8 +169,8 @@ function setupKillAndExit() {
177169
err = process._kill(pid, 0);
178170
} else {
179171
sig = sig || 'SIGTERM';
180-
if (lazyConstants()[sig]) {
181-
err = process._kill(pid, lazyConstants()[sig]);
172+
if (constants[sig]) {
173+
err = process._kill(pid, constants[sig]);
182174
} else {
183175
throw new Error(`Unknown signal: ${sig}`);
184176
}
@@ -198,7 +190,7 @@ function setupSignalHandlers() {
198190
const signalWraps = {};
199191

200192
function isSignal(event) {
201-
return typeof event === 'string' && lazyConstants()[event] !== undefined;
193+
return typeof event === 'string' && constants[event] !== undefined;
202194
}
203195

204196
// Detect presence of a listener for the special signal types
@@ -212,7 +204,7 @@ function setupSignalHandlers() {
212204

213205
wrap.onsignal = function() { process.emit(type); };
214206

215-
const signum = lazyConstants()[type];
207+
const signum = constants[type];
216208
const err = wrap.start(signum);
217209
if (err) {
218210
wrap.close();

‎lib/internal/process/stdio.js

+4-14
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

+9-17
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

+5-12
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;
@@ -1023,7 +1025,6 @@ Socket.prototype.connect = function(...args) {
10231025

10241026

10251027
function lookupAndConnect(self, options) {
1026-
const dns = lazyDns();
10271028
var host = options.host || 'localhost';
10281029
var port = options.port;
10291030
var localAddress = options.localAddress;
@@ -1371,18 +1372,11 @@ function emitListeningNT(self) {
13711372
}
13721373

13731374

1374-
function lazyDns() {
1375-
if (dns === undefined)
1376-
dns = require('dns');
1377-
return dns;
1378-
}
1379-
1380-
13811375
function listenInCluster(server, address, port, addressType,
13821376
backlog, fd, exclusive) {
13831377
exclusive = !!exclusive;
13841378

1385-
if (!cluster) cluster = require('cluster');
1379+
if (cluster === null) cluster = require('cluster');
13861380

13871381
if (cluster.isMaster || exclusive) {
13881382
// Will create a new handle
@@ -1491,7 +1485,6 @@ Server.prototype.listen = function(...args) {
14911485
};
14921486

14931487
function lookupAndListen(self, port, address, backlog, exclusive) {
1494-
const dns = lazyDns();
14951488
dns.lookup(address, function doListen(err, ip, addressType) {
14961489
if (err) {
14971490
self.emit('error', err);

‎lib/readline.js

+2-4
Original file line numberDiff line numberDiff line change
@@ -28,8 +28,9 @@
2828
'use strict';
2929

3030
const { debug, inherits } = require('util');
31-
const Buffer = require('buffer').Buffer;
31+
const { Buffer } = require('buffer');
3232
const EventEmitter = require('events');
33+
const { StringDecoder } = require('string_decoder');
3334
const {
3435
CSI,
3536
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
}
@@ -177,7 +177,6 @@ function Interface(input, output, completer, terminal) {
177177
input.removeListener('data', ondata);
178178
input.removeListener('end', onend);
179179
});
180-
var StringDecoder = require('string_decoder').StringDecoder; // lazy load
181180
this._decoder = new StringDecoder('utf8');
182181

183182
} else {
@@ -979,7 +978,6 @@ Interface.prototype._ttyWrite = function(s, key) {
979978

980979
function emitKeypressEvents(stream, iface) {
981980
if (stream[KEYPRESS_DECODER]) return;
982-
var StringDecoder = require('string_decoder').StringDecoder; // lazy load
983981
stream[KEYPRESS_DECODER] = new StringDecoder('utf8');
984982

985983
stream[ESCAPE_DECODER] = emitKeys(stream);

0 commit comments

Comments
 (0)
Please sign in to comment.