Create a gist now

Instantly share code, notes, and snippets.

@chrisdickinson /bench-1.js Secret
Last active Apr 24, 2016

What would you like to do?
var Point = require('./' + (process.env.WHICH || 'closure'))
var iter = 1000000
var rand = Math.random
var hrtime = process.hrtime()
for (var i = 0; i < iter; ++i) {
var p = new Point(rand(), rand(), rand(), rand())
for (var j = 0; j < 1000; ++j) {
p.distance()
}
}
hrtime = process.hrtime(hrtime)
console.log(
'%smb, %sms'
, process.memoryUsage().heapTotal / 1048576
, hrtime[0] * 1e3 + hrtime[1] / 1e6
)
// ./bench.js
var Point = require('./' + (process.env.WHICH || 'proto'))
var iter = (1000000 * 1000)
var rand = Math.random
var hrtime = process.hrtime()
var p = new Point(rand(), rand(), rand(), rand())
, t = 0
for (var i = 0; i < iter; ++i) {
t += p.distance()
}
hrtime = process.hrtime(hrtime) // get the difference since original measurement
console.log(
'%sms'
, hrtime[0] * 1e3 + hrtime[1] / 1e6
)
// ./closure.js
// the closure utilizing version
module.exports = Point
function Point(x0, y0, x1, y1) {
this.distance = function dist() {
var x = x1 - x0
var y = y1 - y0
return Math.sqrt(x * x + y * y)
}
}
module.exports = Point
function Point(x0, y0, x1, y1) {
this.x0 = x0
this.x1 = x1
this.y0 = y0
this.y1 = y1
this.distance = function distance() {
var x = this.x1 - this.x0
, y = this.y1 - this.y0
return Math.sqrt(x * x + y * y)
}
}
// ./proto.js
// the prototype-utilizing version
module.exports = Point
function Point(x0, y0, x1, y1) {
this.x0 = x0
this.y0 = y0
this.x1 = x1
this.y1 = y1
}
Point.prototype.distance = function() {
var x = this.x1 - this.x0
, y = this.y1 - this.y0
return Math.sqrt(x * x + y * y)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment