Skip to content

Instantly share code, notes, and snippets.

@mraleph
Created February 26, 2011 16:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mraleph/845334 to your computer and use it in GitHub Desktop.
Save mraleph/845334 to your computer and use it in GitHub Desktop.
// This is modified version of benchmark from http://d.hatena.ne.jp/sumim/20110217/p1
//
// It is ~35% faster when I run it on the recent nodejs compiled for ia32 (V8 3.1.6).
//
// mraleph@whitestar|~/src/node/% ./node test.js
// 0
// 3.509
// mraleph@whitestar|~/src/node/% ./node test-original.js
// 0
// 5.344
//
// The secret behind the speedup is simple: I've given V8 a chance to inline calc into loop thus
// removing boxing/unboxing of argument/return value.
//
// -- Vyacheslav Egorov
//
function Looping(){
this.n0 = 0;
this.calc = function(n){
var n1 = this.n0 + (1 - 2*((n+2)%2));
this.n0 = n;
return n1;
}
}
var l = new Looping();
var t1 = new Date();
// For some reason V8 does not consider calc for inlining if I declare loop as
// function loop () { ... }
// I am still investigating why.
var loop = new Function("l", "var n = 1; for(var c=0;c<268435455;c++) n = l.calc(n); return n;");
var n = loop(l);
console.log("%s\n%s", n, (new Date() - t1) / 1000);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment