Pub/Sub implementations

JavaScript performance comparison

Revision 3 of this test case created by

Preparation code

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script>
  /*	
  
  	jQuery pub/sub plugin by Peter Higgins (dante@dojotoolkit.org)
  
  	Loosely based on Dojo publish/subscribe API, limited in scope. Rewritten blindly.
  
  	Original is (c) Dojo Foundation 2004-2010. Released under either AFL or new BSD, see:
  	http://dojofoundation.org/license for more information.
  
  */
  (function($) {
   var topics = {};
  
   $.publish1 = function(topic, args) {
    if (topics[topic]) {
     var currentTopic = topics[topic];
  
     for (var i = 0, j = currentTopic.length; i < j; i++) {
      currentTopic[i].apply($, args || []);
     }
    }
   };
  
   $.subscribe1 = function(topic, callback) {
    if (!topics[topic]) {
     topics[topic] = [];
    }
  
    topics[topic].push(callback);
  
    return {
     "topic": topic,
     "callback": callback
    };
   };
  
   $.unsubscribe1 = function(handle) {
    var topic = handle.topic;
  
    if (topics[topic]) {
     var currentTopic = topics[topic];
  
     for (var i = 0, j = currentTopic.length; i < j; i++) {
      if (currentTopic[i] === handle.callback) {
       currentTopic.splice(i, 1);
      }
     }
    }
   };
  
  })(jQuery);
  
  /*!
   * jQuery Tiny Pub/Sub - v0.3pre - 11/4/2010
   * http://benalman.com/
   * 
   * Copyright (c) 2010 "Cowboy" Ben Alman
   * Dual licensed under the MIT and GPL licenses.
   * http://benalman.com/about/license/
   */
  /*!
   * jQuery Tiny Pub/Sub - v0.X - 11/18/2010
   * http://benalman.com/
   * 
   * Original Copyright (c) 2010 "Cowboy" Ben Alman
   * Dual licensed under the MIT and GPL licenses.
   * http://benalman.com/about/license/
   *
   * Made awesome by Rick Waldron
   *
   */
  (function(jQuery) {
   var o = jQuery({});
   jQuery.each({
    "subscribe2": "bind",
    "unsubscribe2": "unbind",
    "publish2": "trigger"
   }, function(fn, api) {
    jQuery[fn] = function() {
     o[api].apply(o, arguments);
    };
   });
  })(jQuery);
</script>
    

Preparation code output

Test runner

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

Java applet disabled.

Testing in CCBot 2.0.0 / Other 0.0.0
Test Ops/sec
Object cache
var handle = $.subscribe1('foo', function() {
 1 + 1;
});

$.publish1('foo', ['bar']);

$.unsubscribe1(handle);
pending…
jQuery events
$.subscribe2('foo', function() {
 1 + 1;
});

$.publish2('foo', ['bar']);

$.unsubscribe2('foo');
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.

2 Comments

Drew Wells commented :

wow, good catch. These are the results I was expecting. I could not figure out how the jQuery one was faster than the extremely small pub/sub by Higgins.

jkjn commented :

kjkjkj