Skip to content

Commit 72fb281

Browse files
evanlucasMyles Borins
authored and
Myles Borins
committed
util: improve util.format performance
By manually copying arguments and breaking the try/catch out, we are able to improve the performance of util.format by 20-100% (depending on the types). PR-URL: #5360 Reviewed-By: James M Snell <[email protected]>
1 parent f152adf commit 72fb281

File tree

1 file changed

+22
-13
lines changed

1 file changed

+22
-13
lines changed

lib/util.js

+22-13
Original file line numberDiff line numberDiff line change
@@ -9,39 +9,48 @@ const isError = internalUtil.isError;
99

1010
var Debug;
1111

12+
function tryStringify(arg) {
13+
try {
14+
return JSON.stringify(arg);
15+
} catch (_) {
16+
return '[Circular]';
17+
}
18+
}
19+
1220
const formatRegExp = /%[sdj%]/g;
1321
exports.format = function(f) {
1422
if (typeof f !== 'string') {
15-
var objects = [];
23+
const objects = new Array(arguments.length);
1624
for (var index = 0; index < arguments.length; index++) {
17-
objects.push(inspect(arguments[index]));
25+
objects[index] = inspect(arguments[index]);
1826
}
1927
return objects.join(' ');
2028
}
2129

2230
if (arguments.length === 1) return f;
2331

24-
var i = 1;
25-
var args = arguments;
26-
var len = args.length;
27-
var str = String(f).replace(formatRegExp, function(x) {
32+
const len = arguments.length;
33+
const args = new Array(len);
34+
var i;
35+
for (i = 0; i < len; i++) {
36+
args[i] = arguments[i];
37+
}
38+
39+
i = 1;
40+
var str = f.replace(formatRegExp, function(x) {
2841
if (x === '%%') return '%';
2942
if (i >= len) return x;
3043
switch (x) {
3144
case '%s': return String(args[i++]);
3245
case '%d': return Number(args[i++]);
33-
case '%j':
34-
try {
35-
return JSON.stringify(args[i++]);
36-
} catch (_) {
37-
return '[Circular]';
38-
}
46+
case '%j': return tryStringify(args[i++]);
3947
// falls through
4048
default:
4149
return x;
4250
}
4351
});
44-
for (var x = args[i]; i < len; x = args[++i]) {
52+
while (i < len) {
53+
const x = args[i++];
4554
if (x === null || (typeof x !== 'object' && typeof x !== 'symbol')) {
4655
str += ' ' + x;
4756
} else {

0 commit comments

Comments
 (0)