This repository has been archived by the owner. It is now read-only.
Permalink
Browse files

Optimize for few args in EventEmitter.emit

  • Loading branch information...
ry committed Apr 23, 2010
1 parent 6abdf05 commit 0633e5cac981cf6433baeea581b34461e3f82dc2
Showing with 15 additions and 6 deletions.
  1. +15 −6 lib/events.js
View
@@ -2,9 +2,10 @@ exports.EventEmitter = process.EventEmitter;
process.EventEmitter.prototype.emit = function (type) {
- if (type == 'error') {
+ // If there is no 'error' event listener then throw.
+ if (type === 'error') {
if (!this._events || !this._events.error ||
- (this._events.error instanceof Array && !this._events.error.length))
+ (this._events.error instanceof Array && !this._events.error.length))
{
if (arguments[1] instanceof Error) {
throw arguments[1];
@@ -19,15 +20,23 @@ process.EventEmitter.prototype.emit = function (type) {
if (!this._events[type]) return false;
if (typeof this._events[type] == 'function') {
- var args = Array.prototype.slice.call(arguments, 1);
-
- this._events[type].apply(this, args);
+ if (arguments.length < 3) {
+ // fast case
+ this._events[type].call( this

This comment has been minimized.

Show comment Hide comment
@ry

ry Apr 23, 2010

yes, it's faster. (faster 'cause it doesn't have to create the args array.)

@ry

ry Apr 23, 2010

yes, it's faster. (faster 'cause it doesn't have to create the args array.)

+ , arguments[1]
+ , arguments[2]
+ );
+ } else {
+ // slower
+ var args = Array.prototype.slice.call(arguments, 1);
+ this._events[type].apply(this, args);
+ }
return true;
} else if (this._events[type] instanceof Array) {
var args = Array.prototype.slice.call(arguments, 1);
-
+
var listeners = this._events[type].slice(0);
for (var i = 0, l = listeners.length; i < l; i++) {
listeners[i].apply(this, args);

0 comments on commit 0633e5c

Please sign in to comment.