A few quick tests to see how much speed you lose by evaluating pre-parsed statements, rather than generating a function with new Function(...)
to do it for you. Follows this discussion.
Open a new tab to about:blank, open the console, copy and paste test.js
. The results I get:
inline statement: 1.847ms
normal function: 1.852ms
generated function: 1.707ms
naive evaluation: 35.201ms
primed evaluation: 8.932ms
Interestingly, a generated function is just as fast as an inline statement. (I tried including eval
in this test, but it's so shockingly slow that I had to close the tab. We're talking 2-3 orders of magnitude slower.) Evaluating code yourself is ~4.5x slower - given that we're still talking about >100m/sec for the example at hand, it's unlikely to be a bottleneck in any real-world apps, but we certainly don't gain any performance (though we do gain CSP compliance and the ability to thwart certain attacks).
The generated function running faster is indeed strange.
However, if we change the test to include the time to create the function:
normal functions win hands down: