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

Note: This code is not representative of how event signaling should be implemented in a class. However, it accurately reflects how the code that I'm interested in using is structured.

Running this on a Cloud9 instance (backed by OpenShift, Node.js v0.8.9), the numbers are strikingly different in the event emitter implementation's favor. Over 10 runs of 10 seconds each the event-based counter averaged 2086576 iterations, compared to 1706415 iterations using the callback. This is a 22% performance improvement using events.

Running the same script on a local machine (2.4 GHz Core 2 Duo, Node.js v0.8.11) produced results so much better that they could be characterized as simply astounding. Over 10 runs of 10 seconds each the event-based counter averaged 51817596 iterations, compared to 26675674 iterations using the callback. This is a _94%_ performance improvement.

Conclusion: use events, not callbacks.

@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