Skip to content

Instantly share code, notes, and snippets.

@coto
Last active January 5, 2016 21:43
Show Gist options
  • Save coto/720759 to your computer and use it in GitHub Desktop.
Save coto/720759 to your computer and use it in GitHub Desktop.
JavaScript Benchmark - Closure vs Prototype
<html>
<head>
<title>Becnhmark - Javascript prototype versus closure execution speed</title>
<script type="text/javascript">
/*
* Author: Coto Augosto
* Twitter: http://twitter.com/coto
* URL: http://beecoss.com
* Created: Nov 30, 2010
*/
// Prototype implementation
function PixelP(x, y) {
this.x = x;
this.y = y;
}
PixelP.prototype.getX = function() {
return this.x;
}
PixelP.prototype.getY = function() {
return this.y;
}
PixelP.prototype.setX = function(value) {
this.x = value;
}
PixelP.prototype.setY = function(value) {
this.y = value;
}
// Closure implementation
function Pixel(x, y) {
this.x = x;
this.y = y;
this.getX = function() {
return this.x;
}
this.getY = function() {
return this.y;
}
this.setX = function(value) {
this.x = value;
}
this.setY = function(value) {
this.y = value;
}
}
const CYCLES = 2000000;
function TestPerformance() {
// Testing Instance
var prototypeStartDateTime = new Date();
for (var i = 0; i < CYCLES; i++) {
var x = new PixelP(i, i);
}
var prototypeEndDateTime = new Date();
var closureStartDateTime = new Date();
for (var i = 0; i < CYCLES; i++) {
var x = new Pixel(i, i);
}
var closureEndDateTime = new Date();
var closureTime = closureEndDateTime.getTime() - closureStartDateTime.getTime();
var prototypeTime = prototypeEndDateTime.getTime() - prototypeStartDateTime.getTime();
console.log("Instance Time");
console.log("Closure: " + closureTime + " v/s Prototype: " + prototypeTime + " ->> \"PROTOTYPE IS " + parseInt(closureTime/prototypeTime) + " TIMES FASTER\"");
// Testing Execution
var prototypeExecStartDateTime, prototypeExecEndDateTime;
function getTimePrototype() {
var cl2 = new PixelP(1, 1000);
prototypeExecStartDateTime = new Date();
for (var i = 0; i < CYCLES; i++) {
cl2.setX('hola');
}
prototypeExecEndDateTime = new Date();
}
var closureExecStartDateTime, closureExecEndDateTime;
function getTimeClosure(){
var cl1 = new Pixel(1, 1000);
closureExecStartDateTime = new Date();
for (var i = 0; i < CYCLES; i++) {
cl1.setX('hola');
}
closureExecEndDateTime = new Date();
}
getTimePrototype();
getTimeClosure();
var closureExecTime = closureExecEndDateTime.getTime() - closureExecStartDateTime.getTime();
var prototypeExecTime = prototypeExecEndDateTime.getTime() - prototypeExecStartDateTime.getTime();
console.log("Execution Time");
console.log("Closure: " + closureExecTime + " v/s Prototype: " + prototypeExecTime + " ->> \"PROTOTYPE IS " + parseInt(closureExecTime/prototypeExecTime) + " TIMES FASTER\"");
}
TestPerformance();
</script>
</head>
<body>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment