diff options
author | Ben Noordhuis <info@bnoordhuis.nl> | 2012-06-27 19:15:28 +0200 |
---|---|---|
committer | Ben Noordhuis <info@bnoordhuis.nl> | 2012-06-28 03:51:42 +0200 |
commit | 6531f187d877da403af0bbe5aa9814705e5ace61 (patch) | |
tree | fc3ae6a03b790c41d019a512d93a61fe44d9a5fa /lib/util.js | |
parent | be3afd0becdff628c4e57c90b889210ae7db7a23 (diff) | |
download | node-new-6531f187d877da403af0bbe5aa9814705e5ace61.tar.gz |
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.
Diffstat (limited to 'lib/util.js')
-rw-r--r-- | lib/util.js | 21 |
1 files changed, 18 insertions, 3 deletions
diff --git a/lib/util.js b/lib/util.js index 580aa81192..65888920c8 100644 --- a/lib/util.js +++ b/lib/util.js @@ -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 @@ -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) { @@ -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) { |