Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Map optimization : each boiler #1708

Merged
merged 1 commit into from
Jun 27, 2014
Merged
Changes from all commits
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
19 changes: 13 additions & 6 deletions underscore.js
Original file line number Diff line number Diff line change
Expand Up @@ -112,13 +112,20 @@
};

// Return the results of applying the iterator to each element.
_.map = _.collect = function(obj, iterator, context) {
var results = [];
if (obj == null) return results;
_.map = _.collect = function(obj, iterator, context) {
Copy link
Contributor

Choose a reason for hiding this comment

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

It looks as though there's an extra space at the beginning of this line.

if (obj == null) return [];
iterator = lookupIterator(iterator, context);
_.each(obj, function(value, index, list) {
results.push(iterator(value, index, list));
});
var length = obj.length,
currentKey, keys;
if (length !== +length) {
keys = _.keys(obj);
length = keys.length;
}
var results = Array(length);
for (var index = 0; index < length; index++) {
currentKey = keys ? keys[index] : index;
Copy link
Collaborator

Choose a reason for hiding this comment

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

You shouldn't test keys in the loop. For optimum performance, we should pull the keys test out and have two loops: one that accesses keys[index] and one that uses index directly.

Copy link
Contributor

Choose a reason for hiding this comment

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

You've brought this up with other parts of Underscore in the past & I believe at the time it was proven that the check was negligible. We can check again to validate but avoiding the second loop is a big win for avoiding code dup.

Copy link
Collaborator

Choose a reason for hiding this comment

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

Oh, I didn't realise. I'm not super opinionated either way. We'll stick with the simpler style.

results[index] = iterator(obj[currentKey], currentKey, obj);
}
return results;
};

Expand Down