diff options
author | Brian White <mscdex@mscdex.net> | 2020-06-06 14:18:46 -0400 |
---|---|---|
committer | Brian White <mscdex@mscdex.net> | 2020-06-08 15:21:13 -0400 |
commit | 4ba90809edec189a2c4662258ef6cadb9d9620b4 (patch) | |
tree | 23e8b60e988b871adb6a54f598dd29a4b676747c /lib/events.js | |
parent | 651088c3e6b6399a3e656e397c3845b970ad7903 (diff) | |
download | node-new-4ba90809edec189a2c4662258ef6cadb9d9620b4.tar.gz |
events: improve arrayClone performance
PR-URL: https://github.com/nodejs/node/pull/33774
Reviewed-By: Robert Nagy <ronagy@icloud.com>
Reviewed-By: James M Snell <jasnell@gmail.com>
Reviewed-By: Benjamin Gruenbaum <benjamingr@gmail.com>
Reviewed-By: Michaƫl Zasso <targos@protonmail.com>
Reviewed-By: Zeyu Yang <himself65@outlook.com>
Diffstat (limited to 'lib/events.js')
-rw-r--r-- | lib/events.js | 20 |
1 files changed, 13 insertions, 7 deletions
diff --git a/lib/events.js b/lib/events.js index a5af5ff930..06fed54c61 100644 --- a/lib/events.js +++ b/lib/events.js @@ -322,7 +322,7 @@ EventEmitter.prototype.emit = function emit(type, ...args) { } } else { const len = handler.length; - const listeners = arrayClone(handler, len); + const listeners = arrayClone(handler); for (let i = 0; i < len; ++i) { const result = ReflectApply(listeners[i], this, args); @@ -560,7 +560,7 @@ function _listeners(target, type, unwrap) { return unwrap ? [evlistener.listener || evlistener] : [evlistener]; return unwrap ? - unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length); + unwrapListeners(evlistener) : arrayClone(evlistener); } EventEmitter.prototype.listeners = function listeners(type) { @@ -599,11 +599,17 @@ EventEmitter.prototype.eventNames = function eventNames() { return this._eventsCount > 0 ? ReflectOwnKeys(this._events) : []; }; -function arrayClone(arr, n) { - const copy = new Array(n); - for (let i = 0; i < n; ++i) - copy[i] = arr[i]; - return copy; +function arrayClone(arr) { + // At least since V8 8.3, this implementation is faster than the previous + // which always used a simple for-loop + switch (arr.length) { + case 2: return [arr[0], arr[1]]; + case 3: return [arr[0], arr[1], arr[2]]; + case 4: return [arr[0], arr[1], arr[2], arr[3]]; + case 5: return [arr[0], arr[1], arr[2], arr[3], arr[4]]; + case 6: return [arr[0], arr[1], arr[2], arr[3], arr[4], arr[5]]; + } + return arr.slice(); } function unwrapListeners(arr) { |