Skip to content

Instantly share code, notes, and snippets.

@gizmotronic
Created June 30, 2013 01:51
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gizmotronic/5893457 to your computer and use it in GitHub Desktop.
Save gizmotronic/5893457 to your computer and use it in GitHub Desktop.
Compare Node.js event signaling using callbacks vs. the event emitter class
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()
@gizmotronic
Copy link
Author

I've recorded similar results using Node.js v0.6.20, with an overall improvement by using event emitters over callbacks of 73%.

@gizmotronic
Copy link
Author

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