Skip to content

Instantly share code, notes, and snippets.

@mraleph
Created February 27, 2011 12:40
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/846148 to your computer and use it in GitHub Desktop.
Save mraleph/846148 to your computer and use it in GitHub Desktop.
// NB: this micro-benchmark is stupid in a sense that all loops can be potentially optimized away
// but it's only purpose is to show that variable accesses become slower when eval is in the same scope.
// -- Vyacheslav Egorov
function foo () {
var j = 0;
for (var i = 0; i < 1e7; i++) j = i;
for (var i = 0; i < 1e7; i++) j = i;
for (var i = 0; i < 1e7; i++) j = i;
return j;
}
function bar () {
var j = 0;
for (var i = 0; i < 1e7; i++) j = i;
for (var i = 0; i < 1e7; i++) j = i;
for (var i = 0; i < 1e7; i++) j = i;
eval("");
return j;
}
function baz () {
function baz1() {
var j = 0;
for (var i = 0; i < 1e7; i++) j = i;
for (var i = 0; i < 1e7; i++) j = i;
for (var i = 0; i < 1e7; i++) j = i;
return j;
}
eval("");
return baz1();
}
function qux () {
var j = 0;
function qux1() {
for (var i = 0; i < 1e7; i++) j = i;
for (var i = 0; i < 1e7; i++) j = i;
for (var i = 0; i < 1e7; i++) j = i;
}
qux1();
return j;
}
function quux () {
var j = 0;
function quux1() {
for (var i = 0; i < 1e7; i++) j = i;
for (var i = 0; i < 1e7; i++) j = i;
for (var i = 0; i < 1e7; i++) j = i;
}
eval("");
quux1();
return j;
}
function m (f) {
var s = Date.now();
f();
print(Date.now() - s);
}
m(foo);
m(bar);
m(baz);
m(qux);
m(quux);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment