Here is a code snippet that I have been experimenting with:
function Run () {
var n = 2*1e7;
var inside = 0;
while (n--) {
if (Math.pow(Math.random(), 2) +
Math.pow(Math.random(), 2) < 1)
inside++;
}
return inside;
}
var start = Date.now();
Run();
console.log(Date.now() - start);
Initially, the output time is around 335ms. Quite impressive! However, when I enclose the Run function within an anonymous self-invoking function like this:
var d = Date.now();
(function Run () {
var n = 2*1e7;
var inside = 0;
while (n--) {
if (Math.pow(Math.random(), 2) +
Math.pow(Math.random(), 2) < 1)
inside++;
}
return inside;
})();
console.log(Date.now() - d);
The output drastically increases to 18319ms. This performance degradation is perplexing. Do you know why this happens?
Just for reference, I am running these snippets on Chrome 26.0.1410.63 console. Interestingly, both versions perform well in the node.js console.