The case against eval
The case against
eval() generally centers around safety. It is always a terrible idea to intentionally allow
your programs to execute code you didn’t write or can’t validate the source or intent of.
The question then, is that if a string isn’t generated by a user, is
eval ok to use?
The answer is no; though the reason isn’t safety, but performance.
If the engine finds an
eval(...) statement in the code, it effectively has to assume that all the pre-execution
identifier location information it has might be invalid, since it can’t know if, at run time, the code passed to
eval(...) will modify a given lexical scope. Since most of the optimizations it would make would
be pointless if
eval(...) modified a scope, the compiler simply doesn’t perform the optimizations at all.
This problem is not unique to
with (and its function of creating new lexical scopes based on the object properties passed to it)
causes the same problem and results in the code not being optimized.
The only way around the problem, if you simply cannot avoid using
eval, is to isolate that code in a separate file
that can be loaded and compiled separately from the rest of the application code.