First, performance (especially x100 slower) should be enough reason to not use something.
However, you are missing the point. You are now asking "why not use eval
in the specific example of evaluating a function in a string?". Well, the answer of that is because you have a function called str2func
to specifically do this job faster and more safely. The reason you should not use eval is because in the cases you want to use eval, the logic of your code is flawed.
The only reason to eval
is to evaluate an arbitrary input that is not just a function on a string (why would you do that, you already showed that there is an specific function for it). If you know what you are evaluating, then you don't need eval, you can write code for what you expect. Thus, eval
is only of use when you accept generic inputs. But generic inputs include rm -rf
to delete your whole OS. Or in a less catastrophic case, the code may rewrite over a variable that is important for the rest of the algorithm. It is obvious why you dont want to let your code run arbitrary inputs.
What about dynamic variables? A terrible idea that can be generated using eval
. And you may accidentally make this by accepting arbitrary inputs.
But there are more things. eval
does make your code unreadable. You have no idea what the code does, until runtime.
I have seen code that does this within its core functions
model.solve_algorithm=eval(['default(',[ class(input3) ],')']);
result=eval(model.solve_algorithm);
What does the code do? What are the options? There is no way to know, unless you run it, and see where it goes. This makes the code obfuscated and hard to read, and certainly hard to maintain. Being explicit in code is something that does benefit a lot in maintainability of code.
TLDR: In any case that you may want to use eval, one of the two is happening:
- There is a better, more specific function for what you want to do
- You really should not be doing what you are trying to do, code/logic needs restructuring.