matlab - Performance of `eval` compared to `str2func` to evalulate a function from a string -
eval , str2func both able evaluate function represented string, f.e. f='a^x+exp(b)+sin(c*x)+d':
using
eval:y = eval(f)or (suggested 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 best performance?
remarks
note benchmark inspired on this question.
note i'm aware using eval , str2func bad practice[1][2] (as mentioned in comments).
short answer: use str2func.
benchmark
the benchmark evaluate function n different values of x.
f='a^x+exp(b)+sin(c*x)+d'; ns = linspace(1, 1000, 20); timeeval = zeros(size(ns)); timeevalhandle = zeros(size(ns)); timestr2func = zeros(size(ns)); i=1:length(ns) n = ns(i); timeeval(i) = timeit(@() useeval(f, n)); timeevalhandle(i) = timeit(@() useevalhandle(f, n)); timestr2func(i) = timeit(@() usestr2func(f, n)); end figure plot(ns, timeeval, 'displayname', 'time eval'); hold on plot(ns, timeevalhandle, 'displayname', 'time eval'); hold on plot(ns, timestr2func, 'displayname', 'time str2func'); legend show xlabel('n'); figure plot(ns, timeeval./timestr2func, 'displayname', 'time_{eval}/time_{str2func}'); hold on plot(ns, timeevalhandle./timestr2func, 'displayname', 'time_{eval handle}/time_{str2func}'); legend show xlabel('n'); figure plot(ns, timeevalhandle./timestr2func); ylabel('time_{eval handle}/time_{str2func}') xlabel('n'); function y = useeval(f, n) = 1; b = 2; c = 3; d = 4; x=1:n y = eval(f); end end function y = useevalhandle(f, n) = 1; b = 2; c = 3; d = 4; fhandle = eval(['@(x, a, b, c, d) ' f]); x=1:n y = fhandle(x, a, b, c, d); end end function y = usestr2func(f, n) = 1; b = 2; c = 3; d = 4; fhandle = str2func(['@(x, a, b, c, d) ' f]); x=1:n y = fhandle(x, a, b, c, d); end end str2func vs eval (without function handle): results show evaluating function once, around 50% faster use str2func eval (without function handle). large number of evaluations, str2func may around 100x faster (depending on function evaluating).
str2func vs eval (with function handle): eval around 100% slower str2func single evaluation, becomes equally fast large number of evaluations (eval ~5% slower).
eval , without function handle: note single evaluation creating function handle eval ~50% slower evaluating directly.
conclusion: str2func faster eval.



Comments
Post a Comment