2

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?

MaiaVictor
  • 51,090
  • 44
  • 144
  • 286
  • http://stackoverflow.com/a/86580/1169519 – Teemu Dec 30 '14 at 18:46
  • 2
    I suspect this is a very browser and OS specific question that can't be answered easily. I recommend you setup a test on jsperf.com, for example: http://jsperf.com/smallest-timeout and see how this routine turns out across devices. – pp19dd Dec 30 '14 at 18:47
  • 1
    [There you go.](http://jsperf.com/eval-vs-static-function) – MaiaVictor Dec 30 '14 at 18:52

0 Answers0