I am trying to experiment to see if local variables are stored in functions on the stack.
So I wrote a small performance test
function test(fn, times){ var i = times; var t = Date.now() while(i--){ fn() } return Date.now() - t; } ene function straight(){ var a = 1 var b = 2 var c = 3 var d = 4 var e = 5 a = a * 5 b = Math.pow(b, 10) c = Math.pow(c, 11) d = Math.pow(d, 12) e = Math.pow(e, 25) } function inversed(){ var a = 1 var b = 2 var c = 3 var d = 4 var e = 5 e = Math.pow(e, 25) d = Math.pow(d, 12) c = Math.pow(c, 11) b = Math.pow(b, 10) a = a * 5 }
I expected the feedback function to work much faster. Instead, an amazing result appeared.
Until I test one of the functions, it works 10 times faster than after testing the second.
Example:
> test(straight, 10000000) 30 > test(straight, 10000000) 32 > test(inversed, 10000000) 390 > test(straight, 10000000) 392 > test(inversed, 10000000) 390
The same behavior when testing in an alternative order.
> test(inversed, 10000000) 25 > test(straight, 10000000) 392 > test(inversed, 10000000) 394
I tested it in both the Chrome browser and Node.js, and I don’t know why this will happen. The effect persists until the current page is refreshed or the Node REPL is restarted.
What could be the source of such significant (12 times worse) performance?
PS. Since it only works in some environments, write the environment that you use to test it.
My were:
OS: Ubuntu 14.04
Node v0.10.37
Chrome 43.0.2357.134 (Official Build) (64-bit)
/ Edit
In Firefox 39, ~ 5500 ms is required for each test, regardless of order. It seems that this only happens on certain engines.
/ Edit2
The inclusion of a function in a test function makes it always work at the same time.
Is it possible that there is an optimization that builds a function parameter if it is always the same function?