Skip to content
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
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>
  • Loading branch information
evanlucas committed Mar 4, 2016
commit 8d72b0d291e603c3b62b637a314a5ee35ba95fdc
35 changes: 22 additions & 13 deletions lib/util.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,39 +9,48 @@ const isError = internalUtil.isError;

var Debug;

function tryStringify(arg) {
try {
return JSON.stringify(arg);
} catch (_) {
return '[Circular]';
}
}

const formatRegExp = /%[sdj%]/g;
exports.format = function(f) {
if (typeof f !== 'string') {
var objects = [];
const objects = new Array(arguments.length);
for (var index = 0; index < arguments.length; index++) {
objects.push(inspect(arguments[index]));
objects[index] = inspect(arguments[index]);
}
return objects.join(' ');
}

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

var i = 1;
var args = arguments;
var len = args.length;
var str = String(f).replace(formatRegExp, function(x) {
const len = arguments.length;
const args = new Array(len);
var i;
for (i = 0; i < len; i++) {
args[i] = arguments[i];
}

i = 1;
var str = f.replace(formatRegExp, function(x) {
if (x === '%%') return '%';
if (i >= len) return x;
switch (x) {
case '%s': return String(args[i++]);
case '%d': return Number(args[i++]);
case '%j':
try {
return JSON.stringify(args[i++]);
} catch (_) {
return '[Circular]';
}
case '%j': return tryStringify(args[i++]);
// falls through
default:
return x;
}
});
for (var x = args[i]; i < len; x = args[++i]) {
while (i < len) {
const x = args[i++];
if (x === null || (typeof x !== 'object' && typeof x !== 'symbol')) {
str += ' ' + x;
} else {
Expand Down