I'm implementing a code editing application which involves compiling code on the fly. Problem is, I've noticed that using eval
on a function makes it slower than normal functions, even after calling it several times. For example:
function bench(f){
var t = Date.now();
f();
console.log((f.name||"")+" time: "+(Date.now()-t)/1000+"s");
};
var arr = [];
g = function g(x){
for (var i=0; i<10000000; ++i)
arr[i] = i;
};
// f is the same as g
f = eval("(function f(x){ for (var i=0; i<10000000; ++i) arr[i] = i; })");
for (var i=0; i<5; ++i) bench(f);
for (var i=0; i<5; ++i) bench(g);
for (var i=0; i<5; ++i) bench(f);
for (var i=0; i<5; ++i) bench(g);
Here, this outputs:
f time: 0.448s
f time: 0.032s
f time: 0.035s
f time: 0.033s
f time: 0.034s
g time: 0.008s
g time: 0.007s
g time: 0.007s
g time: 0.008s
g time: 0.007s
f time: 0.032s
f time: 0.033s
f time: 0.032s
f time: 0.032s
f time: 0.032s
g time: 0.008s
g time: 0.008s
g time: 0.007s
g time: 0.008s
g time: 0.008s
Notice that even after calling f
several times, V8 is still using a version that is slower than the identical g
. Why? Is there any workaround?