Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Commit 72fb281

Browse filesBrowse files
evanlucasMyles Borins
authored andcommitted
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 <jasnell@gmail.com>
1 parent f152adf commit 72fb281
Copy full SHA for 72fb281

File tree

Expand file treeCollapse file tree

1 file changed

+22
-13
lines changed
Open diff view settings
Filter options
Expand file treeCollapse file tree

1 file changed

+22
-13
lines changed
Open diff view settings
Collapse file

‎lib/util.js‎

Copy file name to clipboardExpand all lines: lib/util.js
+22-13Lines changed: 22 additions & 13 deletions
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 (0)
Morty Proxy This is a proxified and sanitized view of the page, visit original site.