Ways to speed up eval() ?

● ARCHIVED · READ-ONLY
Started by peq42_ 6 posts View original ↗
  1. What are the best ways to speed up the execution of code inside a string with eval()?

    I know most people say that eval allows for serious code-breaking problems, but since i'm left with no alternative(new function('string') doesn't work here because of the lack of access to certain things) I need to gather as much information as I can on this.


    I heard(and confirmed on tests) that adding a function before the string and then calling it(like this: "myfunction=function(){"+thestring+"}myfunction()" and then evall all that) speed ups by up to 4x the performance, but I still wonder if there's more I can do, since it's still 10x slower than executing it as normal code
  2. perhaps somehow create a cache of functions that were created by eval, and then call that function instead of re-calling the eval? the initial eval would be the only one actually evall-ing. :)

    That said, dont eval if you can avoid it. Sometimes you cant, it happens. But the best way to speed up the execution of your code is to not use eval at all. Try think of a way around what your trying to achive. :)
  3. And if you tell us what exactly you want to do, we might point you to workarounds...
  4. 1. Is the string defined when the game is booted (i.e. from the database) or is the string determined dynamically during runtime?

    elpeleq42 said:
    but since i'm left with no alternative(new function('string') doesn't work here because of the lack of access to certain things)

    2. What is "certain things", exactly? I use the function constructor plenty for this sort of thing.
  5. Apart from optimizing the function you really can't. The code is getting compiled on the go, meaning it's not in our hands, that is unless you understand the code of Chromium and can optimise the compiler.
    Unless you're building 3rd party plugins that aim for a ton of customizability, oftentimes you can avoid the eval though.
  6. A general alternative to eval, assuming you know ahead of time which variables the formula can use, is something like the following:

    Code:
    var fn = new Function("a", "b", "return " + formula);

    Afterward, you just call it with the variables and it should work. The problem is that eval lets you use all of the local variables declared in the context where the eval is called so caching the execution in a function means you have to restrict which variables your formulas can use.