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

events: optimize listener array cloning #1050

Closed
wants to merge 1 commit into from
Closed
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: 6 additions & 13 deletions lib/events.js
Original file line number Diff line number Diff line change
Expand Up @@ -384,7 +384,7 @@ EventEmitter.prototype.listeners = function listeners(type) {
else if (typeof evlistener === 'function')
ret = [evlistener];
else
ret = arrayClone(evlistener);
ret = arrayClone(evlistener, evlistener.length);
}

return ret;
Expand Down Expand Up @@ -413,16 +413,9 @@ function spliceOne(list, index) {
list.pop();
}

function arrayClone(arr, len) {
var ret;
if (len === undefined)
len = arr.length;
if (len >= 50)
ret = arr.slice();
else {
ret = new Array(len);
for (var i = 0; i < len; i += 1)
ret[i] = arr[i];
}
return ret;
function arrayClone(arr, i) {
var copy = new Array(i);
while (i--)
Copy link
Member

Choose a reason for hiding this comment

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

Curious, is iterating backwards faster than forward?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

According to this jsperf and this jsperf it appears so, at least in this case.

Copy link
Contributor

Choose a reason for hiding this comment

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

Yeah, it's really micro, but I also always do this when possible/sane, idk I guess I just like the way it looks. XD

copy[i] = arr[i];
return copy;
}