Skip to content
Closed
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
Next Next commit
util: use for in instead of while hasOwnProperty
This is a huge performance improvement in case of sparse arrays
when using util.inspect as the hole will simple be skipped.
  • Loading branch information
BridgeAR committed Jul 26, 2017
commit ddd4de4b84ed9c0efce8c657e0eb3675a5a6ad88
33 changes: 22 additions & 11 deletions lib/util.js
Original file line number Diff line number Diff line change
Expand Up @@ -672,22 +672,33 @@ function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
var output = [];
let visibleLength = 0;
let index = 0;
while (index < value.length && visibleLength < ctx.maxArrayLength) {
let emptyItems = 0;
while (index < value.length && !hasOwnProperty(value, String(index))) {
emptyItems++;
index++;
}
if (emptyItems > 0) {
for (const elem in value) {
if (visibleLength === ctx.maxArrayLength)
break;
const i = +elem;
if (index !== i) {
if (i !== i) // Fast NaN check
continue;
const emptyItems = i - index;
const ending = emptyItems > 1 ? 's' : '';
const message = `<${emptyItems} empty item${ending}>`;
output.push(ctx.stylize(message, 'undefined'));
} else {
output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
String(index), true));
index++;
index = i;
visibleLength++;
if (visibleLength === ctx.maxArrayLength)
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Couldn't these previous two lines be merged into if (++visibleLength === ctx.maxArrayLength) ?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done

break;
}
output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
elem, true));
visibleLength++;
index++;
}
if (index < value.length && visibleLength !== ctx.maxArrayLength) {
const len = value.length - index;
const ending = len > 1 ? 's' : '';
const message = `<${len} empty item${ending}>`;
output.push(ctx.stylize(message, 'undefined'));
index = value.length;
}
var remaining = value.length - index;
if (remaining > 0) {
Expand Down