From 555a7c48cf3b038f9627591cf51b68387f8de36a Mon Sep 17 00:00:00 2001 From: Brian White Date: Wed, 4 Mar 2015 22:21:47 -0500 Subject: [PATCH] events: optimize listener array cloning This both switches to a single algorithm for array cloning and also speeds up (by ~100% in the ee-listeners-many benchmark) the "many elements" case that was previously handled by `array.slice()`. PR-URL: https://github.com/iojs/io.js/pull/1050 Reviewed-By: Ben Noordhuis Reviewed-By: Julian Duque --- lib/events.js | 19 ++++++------------- 1 file changed, 6 insertions(+), 13 deletions(-) diff --git a/lib/events.js b/lib/events.js index 02e7ac9514..6bd2a77db2 100644 --- a/lib/events.js +++ b/lib/events.js @@ -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; @@ -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[i] = arr[i]; + return copy; }