Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Faster alternative to eval?

Tags:

People also ask

What can I use instead of eval in Python?

literal_eval may be a safer alternative. literal_eval() would only evaluate literals, not algebraic expressions.

Why we should not use eval in JavaScript?

eval() is a dangerous function, which executes the code it's passed with the privileges of the caller. If you run eval() with a string that could be affected by a malicious party, you may end up running malicious code on the user's machine with the permissions of your webpage / extension.

Why do we use eval in JavaScript?

The eval() method evaluates or executes an argument. If the argument is an expression, eval() evaluates the expression. If the argument is one or more JavaScript statements, eval() executes the statements.


I'm dealing with a web app that uses a home-grown templating system that lets Perl code be embedded in HTML. These statements are executed by the template parser at run-time using eval EXPR.

This is very flexible, but these statements are scattered everywhere, and get executed a lot. eval EXPR (as opposed to eval BLOCK) requires Perl to fire up the interpreter each time, and my profiling reveals that they're a reasonably significant source of slowdown.

Many of the embedded Perl statements are very simple. For example, a template might have a line like this:

<p>Welcome, <!--E: $user->query('name') -->.

Or:

<p>Ticket number <!--E: $user->generate_ticket_number() --> has been generated.

That is, they're just calling object methods. There are more complicated ones, too, though.

I'm hoping to optimize this, and so far have two ideas, both of which are terrible. The first is to rewrite all templates to replace simple calls with tokens like USER:NAME and USER:GENERATETICKETNUMBER, which the parser could then scan for and invoke the appropriate object method. But then instead of dealing with templates that mix HTML and Perl, I would have templates that mix HTML, Perl, and tokens.

The second idea is to try to parse the embedded Perl, figure out what the statement wants to do, and, if it's simple enough, call the appropriate object method via a symbolic reference. This is obviously insane.

Is there some logical solution I'm overlooking?