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

lib: micro-optimize EventEmitter#removeListener() #185

Merged
merged 2 commits into from
Dec 20, 2014
Merged
Show file tree
Hide file tree
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
2 changes: 1 addition & 1 deletion benchmark/common.js
Original file line number Diff line number Diff line change
Expand Up @@ -187,7 +187,7 @@ Benchmark.prototype.end = function(operations) {
Benchmark.prototype.report = function(value) {
var heading = this.getHeading();
if (!silent)
console.log('%s: %s', heading, value.toPrecision(5));
console.log('%s: %s', heading, value.toFixed(0));
process.exit(0);
};

Expand Down
23 changes: 23 additions & 0 deletions benchmark/events/ee-add-remove.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
var common = require('../common.js');
var events = require('events');

var bench = common.createBenchmark(main, {n: [25e4]});

function main(conf) {
var n = conf.n | 0;

var ee = new events.EventEmitter();
var listeners = [];

for (var k = 0; k < 10; k += 1)
listeners.push(function() {});

bench.start();
for (var i = 0; i < n; i += 1) {
for (var k = listeners.length; --k >= 0; /* empty */)
ee.on('dummy', listeners[k]);
for (var k = listeners.length; --k >= 0; /* empty */)
ee.removeListener('dummy', listeners[k]);
}
bench.end(n);
}
9 changes: 8 additions & 1 deletion lib/events.js
Original file line number Diff line number Diff line change
Expand Up @@ -246,7 +246,7 @@ EventEmitter.prototype.removeListener =
list.length = 0;
delete this._events[type];
} else {
list.splice(position, 1);
spliceOne(list, position);
}

if (this._events.removeListener)
Expand Down Expand Up @@ -318,3 +318,10 @@ EventEmitter.listenerCount = function(emitter, type) {
ret = emitter._events[type].length;
return ret;
};

// About 1.5x faster than the two-arg version of Array#splice().
function spliceOne(list, index) {
for (var i = index, k = i + 1, n = list.length; k < n; i += 1, k += 1)
list[i] = list[k];
list.pop();
}