PubSubJS vs. jQuery custom events

JavaScript performance comparison

Revision 87 of this test case created

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://rawgithub.com/mroderick/PubSubJS/master/src/pubsub.js">
</script>
<script src="https://rawgithub.com/BennyC/pubbie/master/build/pubbie.min.js">
</script>
<script>
  var callback1 = function(event) {
      return false;
      };
  var callback2 = function(payload) {
      return true;
      };
  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');
    var eventName;
    //subscribe 5000 times use callback1 function to the custom event for jQuery,
    for (i = 0; i < 5000; i++) {
      eventName = 'my-event-' + i;
      body.bind(eventName, callback1);
    }

    // subscribe 5000 times use callback1 function to the custom event for the plain jQuery object (non-DOM)
    for (i = 0; i < 5000; i++) {
      eventName = 'my-event-' + i;
      someJqueryObject.bind(eventName, callback1);
    }

    // subscribe our callback2 function to the message for PubSub
    for (i = 0; i < 5000; i++) {
      eventName = 'my-event-' + i;
      PubSub.subscribe(eventName, callback2);
    }

    for (i = 0; i < 5000; i++) {
      eventName = 'my-event-' + i;
      pubbie.subscribe(eventName, callback2);
    }

    // Use document instead of 'body' as the anchor for custom events
    doc = $(document)
  });
</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-2345', payload);
pending…
jQuery Object - trigger
someJqueryObject.trigger('my-event-2345', payload);
pending…
PubSub - publish - asyncronous
PubSub.publish('my-event-2345', payload);
pending…
PubSub - publish - syncronous
PubSub.publish('my-event-2345', payload, true);
pending…
pubbie
pubbie.publish('my-event-2345', [payload]);
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:

0 comments

Add a comment