Prototype vs Closures - jQuery Plugin

JavaScript performance comparison

Revision 23 of this test case created by Ben Plum

Preparation code

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>

<div class="person_1"></div>
<div class="person_2"></div>
      
<script>
Benchmark.prototype.setup = function() {
  (function($) {
  	function personOne(name) {
  		this.name = name;
  	}
  	
  	personOne.prototype.getName = function() {
  		return this.name;
  	};
  	
  	personOne.prototype.setName = function(name) {
  		this.name = name;
  	}
  	
  	$.fn.PersonOne = function(method) {
  		return $(this).each(function() {
  			var data = $(this).data("Person-One");
  			if (!data) {
  				$(this).data("Person-One", new personOne());
  			}
  		});
  	};
  })(jQuery);
  
  (function($) {
  	var _name = "";
  	
  	function _init(name) {
  		_name = name;
  		return $(this);
  	}
  	
  	var pub = {
  		getName: function() {
  			return _name;
  		},
  		setName: function(name) {
  			_name = name;
  			return $(this);
  		}
  	};
  	
  	$.fn.PersonTwo = function(method) {
  		if (pub[method]) {
  			return pub[method].apply(this, Array.prototype.slice.call(arguments, 1));
  		} else if (typeof method === 'object' || !method) {
  			return _init.apply(this, arguments);
  		}
  		return this;
  	};
  })(jQuery);

};
</script>

Preparation code output

<div class="person_1"></div> <div class="person_2"></div>

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
Prototype init
$(".person_1").PersonOne();
var p1 = $(".person_1").data("Person-One");
pending…
Closure init
var p2 = $(".person_2").PersonTwo();
pending…
Prototype read
$(".person_1").PersonOne();
var p1 = $(".person_1").data("Person-One");
p1.getName();
pending…
Closure read
var p2 = $(".person_2").PersonTwo();
p2.PersonTwo("getName");
pending…
Prototype write
$(".person_1").PersonOne();
var p1 = $(".person_1").data("Person-One");
p1.setName("John");
pending…
Closure write
var p2 = $(".person_2").PersonTwo();
p2.PersonTwo("setName", "Jim");
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.

0 Comments