Prototype vs Closures - jQuery Plugin (v23)

Revision 23 of this benchmark created by Ben Plum on


Preparation HTML

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

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

Setup

(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);

Test runner

Ready to run.

Testing in
TestOps/sec
Prototype init
$(".person_1").PersonOne();
var p1 = $(".person_1").data("Person-One");
ready
Closure init
var p2 = $(".person_2").PersonTwo();
ready
Prototype read
$(".person_1").PersonOne();
var p1 = $(".person_1").data("Person-One");
p1.getName();
ready
Closure read
var p2 = $(".person_2").PersonTwo();
p2.PersonTwo("getName");
ready
Prototype write
$(".person_1").PersonOne();
var p1 = $(".person_1").data("Person-One");
p1.setName("John");
ready
Closure write
var p2 = $(".person_2").PersonTwo();
p2.PersonTwo("setName", "Jim");
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.