Skip to content
This repository has been archived by the owner on Apr 22, 2023. It is now read-only.

Commit

Permalink
util: speed up formatting of large arrays/objects
Browse files Browse the repository at this point in the history
Don't .indexOf() into the keys array. V8 is smart but not so smart that it
knows how to turn the linear scan into a O(1) lookup.

Fixes #3562.
  • Loading branch information
bnoordhuis committed Jun 28, 2012
1 parent be3afd0 commit 6531f18
Showing 1 changed file with 18 additions and 3 deletions.
21 changes: 18 additions & 3 deletions lib/util.js
Expand Up @@ -175,6 +175,17 @@ function stylizeNoColor(str, styleType) {
}


function arrayToHash(array) {
var hash = {};

array.forEach(function(val, idx) {
hash[val] = true;
});

return hash;
}


function formatValue(ctx, value, recurseTimes) {
// Provide a hook for user-specified inspect functions.
// Check that value is an object with an inspect function on it
Expand All @@ -193,8 +204,12 @@ function formatValue(ctx, value, recurseTimes) {
}

// Look up the keys of the object.
var visibleKeys = Object.keys(value);
var keys = ctx.showHidden ? Object.getOwnPropertyNames(value) : visibleKeys;
var keys = Object.keys(value);
var visibleKeys = arrayToHash(keys);

if (ctx.showHidden) {
keys = Object.getOwnPropertyNames(value);
}

// Some type of object without properties can be shortcutted.
if (keys.length === 0) {
Expand Down Expand Up @@ -334,7 +349,7 @@ function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
str = ctx.stylize('[Setter]', 'special');
}
}
if (visibleKeys.indexOf(key) < 0) {
if (!visibleKeys.hasOwnProperty(key)) {
name = '[' + key + ']';
}
if (!str) {
Expand Down

0 comments on commit 6531f18

Please sign in to comment.