Skip to content
This repository was archived by the owner on Apr 12, 2024. It is now read-only.

perf(orderBy): copy array with slice instead of for loop #9942

Closed
wants to merge 1 commit into from

Conversation

kwypchlo
Copy link
Contributor

@kwypchlo kwypchlo commented Nov 6, 2014

Use array slice method to copy entire array instead of a for loop
http://jsperf.com/new-array-vs-splice-vs-slice/54

var arrayCopy = [];
for (var i = 0; i < array.length; i++) { arrayCopy.push(array[i]); }
return arrayCopy.sort(reverseComparator(comparator, reverseOrder));
return array.slice().sort(reverseComparator(comparator, reverseOrder));
Copy link
Contributor

Choose a reason for hiding this comment

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

The problem with this is that array is not necessarlly an Array. it can be an array-like object. This only works in the Array case.

@caitp caitp added this to the 1.3.x milestone Nov 11, 2014
@caitp
Copy link
Contributor

caitp commented Nov 11, 2014

Can you make sure that this will work with ArrayLike objects (with a test case) and ping me when it's ready?

@jimmywarting
Copy link
Contributor

I'm afraid it doesn't work with ArrayLike object
But this will:

Array.prototype.slice.call({0: "a", 1: "b", length: 2}); // ["a", "b"]

@gkalpak
Copy link
Member

gkalpak commented Nov 12, 2014

Note that a reference to [].slice is already available, so this will do:

return slice.call(array).sort(...);
Not sure about the perf implications though. My feeling is that it will still be preferable than the `for-loop`, but I haven't tested.

@kwypchlo
Copy link
Contributor Author

Sure, I'm going back from vacations tomorrow and I will apply the changes :)

@kwypchlo kwypchlo force-pushed the perf-orderby-filter branch from 1cd391d to 3024501 Compare November 14, 2014 13:20
@kwypchlo
Copy link
Contributor Author

@caitp I've amended the commit to include what @jimmywarting and @gkalpak were suggesting as a fix for array like objects. It looks fine now and it works as expected.

@caitp
Copy link
Contributor

caitp commented Nov 14, 2014

looks ok to me, will land in a few minutes

@caitp caitp closed this in 8eabc54 Nov 14, 2014
caitp pushed a commit to caitp/angular.js that referenced this pull request Nov 14, 2014
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

Successfully merging this pull request may close these issues.

5 participants