JSFiddle - React, Tailwind, and code Playground
by pseudosavant
HTML
<div id="prototype"></div>
<div id="objectMethod"></div>
<div id="globalFunction"></div>
JavaScript
now = function(){
return +new Date();
};
// Create Array
var a = [];
Array.prototype.protoSum = function() {
var l = this.length, s = 0;
for (var i = 0; i < l; s += this[i++]);
return s;
};
a.methodSum = function() {
var l = this.length, s = 0;
for (var i = 0; i < l; s += this[i++]);
return s;
};
sum = function(a) {
var l = a.length, s = 0;
for (var i = 0; i < l; s += a[i++]);
return s;
}
// Fill it with 100000 numberic entries
for (var i = 0; i < 10000; i++) {
a.push(Math.random() * 100000, Math.random() * 100000, Math.random() * 100000, Math.random() * 100000, Math.random() * 100000, Math.random() * 100000, Math.random() * 100000, Math.random() * 100000, Math.random() * 100000, Math.random() * 100000);
}
var perf = {
prototype: { start: 0, end: 0, duration: 0, result: 0, test: function(){
this.result = a.protoSum();
}},
objectMethod: { start: 0, end: 0, duration: 0, result: 0, test: function(){
this.result = a.methodSum();
}},
globalFunction: { start: 0, end: 0, duration: 0, result: 0, test: function(){
this.result = sum(a);
}}
};
for (var i in perf) {
var p= perf[i];
p.start = now();
p.test();
p.end = now();
p.duration = p.end - p.start;
$("#" + i).html(i + ": " + p.result + " (" + p.duration + "ms)");
}