Performance of `eval` compared to `str2func` to evalulate a function from a string

Viewed 405

eval and str2func are both able to evaluate a function represented by a string, f.e. f='a^x+exp(b)+sin(c*x)+d':

  • Using eval:

    y = eval(f)
    

    or (suggested by rahnema1)

    fHandle = eval(['@(x, a, b, c, d) ' f]);
    y = fHandle(x, a, b, c, d);
    
  • Using str2func:

    fHandle = str2func(['@(x, a, b, c, d) ' f]);
    y = fHandle(x, a, b, c, d);
    

Which of both methods has the best performance?

Remarks

Note that this benchmark is inspired on this question.

Note that I'm aware that using eval and str2func is often bad practice[1][2] (as mentioned in the comments).

2 Answers
Related