Skip to content

Commit 6531f18

Browse files
committed
util: speed up formatting of large arrays/objects
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.
1 parent be3afd0 commit 6531f18

File tree

1 file changed

+18
-3
lines changed

1 file changed

+18
-3
lines changed

lib/util.js

Lines changed: 18 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -175,6 +175,17 @@ function stylizeNoColor(str, styleType) {
175175
}
176176

177177

178+
function arrayToHash(array) {
179+
var hash = {};
180+
181+
array.forEach(function(val, idx) {
182+
hash[val] = true;
183+
});
184+
185+
return hash;
186+
}
187+
188+
178189
function formatValue(ctx, value, recurseTimes) {
179190
// Provide a hook for user-specified inspect functions.
180191
// Check that value is an object with an inspect function on it
@@ -193,8 +204,12 @@ function formatValue(ctx, value, recurseTimes) {
193204
}
194205

195206
// Look up the keys of the object.
196-
var visibleKeys = Object.keys(value);
197-
var keys = ctx.showHidden ? Object.getOwnPropertyNames(value) : visibleKeys;
207+
var keys = Object.keys(value);
208+
var visibleKeys = arrayToHash(keys);
209+
210+
if (ctx.showHidden) {
211+
keys = Object.getOwnPropertyNames(value);
212+
}
198213

199214
// Some type of object without properties can be shortcutted.
200215
if (keys.length === 0) {
@@ -334,7 +349,7 @@ function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
334349
str = ctx.stylize('[Setter]', 'special');
335350
}
336351
}
337-
if (visibleKeys.indexOf(key) < 0) {
352+
if (!visibleKeys.hasOwnProperty(key)) {
338353
name = '[' + key + ']';
339354
}
340355
if (!str) {

0 commit comments

Comments
 (0)