PubSubJS vs. jQuery custom events

JavaScript performance comparison

Revision 5 of this test case created by Stephen Crosby

Info

An attempt at showing that PubSubJS is faster than using jQuery custom evens for publish/subscribe style messaging.

It's certainly not as rich in features, and I am happy with that.

Introducing PubSubJS

Preparation code

<script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script src="https://github.com/mroderick/PubSubJS/raw/master/pubsub.min.js"></script>
<script>
  var callback1 = function(event) {
    return false;
  };
  var callback2 = function() {};
  var payload = {
   somekey: 'some value'
  };
  var body;
  var someJqueryObject = $({});
 
  // let's use jQuery.ready to make sure that the DOM is ready,
  // before trying to work with it
  jQuery(function() {
   // we'll use the body element to exchange messages for jQuery
   // if using deeper nested elements, jQuery will be slower, as custom events bubble
   body = $('body');
 
   // subscribe our callback1 function to the custom event for jQuery, only once
   body.bind('my-event', callback1);
 
   // subscribe our callback1 function to the custom event for the plain jQuery object (non-DOM)
   someJqueryObject.bind('my-event', callback1);
 
   // subscribe our callback2 function to the message for PubSub
   PubSub.subscribe('my-event', callback2)
  });
</script>

Preparation code output

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
jQuery DOM - trigger
body.trigger('my-event', payload);
pending…
jQuery Object - trigger
someJqueryObject.trigger('my-event', payload);
pending…
PubSub - publish - asyncronous
PubSub.publish('my-event', payload);
pending…
PubSub - publish - syncronous
PubSub.publish('my-event', payload, true);
pending…

Compare results of other browsers

Revisions

You can edit these tests or add even more tests to this page by appending /edit to the URL. Here’s a list of current revisions for this page:

2 comments

Stephen Crosby (revision owner) commented :

We can double the efficiency of the DOM event by adding 'return false;' to its handler, but of course its still far slower than PubSub custom events on an object.

Stephen Crosby (revision owner) commented :

... and if you trigger events on plain jQuery (non-DOM containing) wrapped sets, you can gain another 50% performance boost. My test is claiming only 38% slower than PubSub which is still a lot slower of course. I'm still not sure why that is. Maybe I'll look into it even further.

Add a comment