Created
June 30, 2013 01:51
-
-
Save gizmotronic/5893457 to your computer and use it in GitHub Desktop.
Compare Node.js event signaling using callbacks vs. the event emitter class
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
EventEmitter = require('events').EventEmitter | |
class TestSubject extends EventEmitter | |
constructor: (callback) -> | |
@callback = callback | |
start: -> | |
started = Date.now() | |
while (Date.now() - started) < 10000 | |
@emit 'fire' | |
if @callback | |
@callback() | |
@emit 'end' | |
limit = 10 | |
result = [] | |
accumulator = [] | |
testCallback = -> | |
count = 0 | |
b = new TestSubject -> | |
count += 1 | |
b.on 'end', -> | |
console.log "Callback counted to #{count}" | |
accumulator.push count | |
testEmitter() | |
console.log 'starting TestCallback' | |
b.start() | |
testEmitter = -> | |
count = 0 | |
b = new TestSubject() | |
b.on 'fire', -> | |
count += 1 | |
.on 'end', -> | |
console.log "Emitter counted to #{count}" | |
accumulator.push count | |
result.push accumulator | |
accumulator = [] | |
limit -= 1 | |
if limit > 0 | |
# Next pass | |
testCallback() | |
else | |
# Dump results | |
console.log result | |
console.log 'starting TestEmitter' | |
b.start() | |
# Start the first test | |
testCallback() |
On the same machine that I used to run the v0.6.20 and v0.8.11 testing, I've installed v0.4.10 to match the latest available on Heroku. On this version callbacks averaged 24468784 iterations, and emitters averaged 35189490 iterations, for an improvement of 44%. This is not as impressive as in newer versions of Node.js but it is still significant.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I've recorded similar results using Node.js v0.6.20, with an overall improvement by using event emitters over callbacks of 73%.