why is the anonymous function slower than a function call
Mostrar comentarios más antiguos
I have the following test. I run a for loop and use it to populate the sigma value of a gaussian distribution. I then either call a function or evaluate the expression directly or call a function handle or use an anonymous function. The latter is the slowest. Why?
Here is my code for the test:
% define inputs
kw.m1 = 0; % mean of gaussian
kw.A1=1; % amplitude of gaussian
x = -500:1:500; % timeline
% prepare for loop
tic
for i = 1:10:100
kw.s1 = i;
% in a for next loop generate different standard deviations for gaussians
% call functions using one of several options
switch callopt
% call function using handle
case 1
feval(@gfun,x,kw.m1,kw.A1,kw.s1);
% call function using name
case 2
gfun(x,kw.m1,kw.A1,kw.s1);
% simply use a for next loop
case 3
kw.A1*exp((-(x-kw.m1).^2)/kw.s1^2);
% anonymous
case 4
gauss = @(inp1,inp2,inp3,inp4) inp1*exp((-(inp2-inp3).^2)/inp4^2);
gauss(kw.A1,x,kw.m1,kw.s1);
end
end
runtime = toc;
and here is my function gfun
function [y] = gfun(x,m,A,s)
% create gaussian
y = A*exp((-(x-m).^2)/s^2);
Respuesta aceptada
Más respuestas (1)
schak
el 19 de Feb. de 2018
0 votos
2 comentarios
Jan
el 19 de Feb. de 2018
Try it. In my experiences arrayfun is nicer, but slower than direct loops.
Adam Wyatt
el 6 de Dic. de 2020
I agree with Jan, arrayfun (and cellfun) are extremely slow compared to direct loops, even in the latest version (R2020b). This may be because the for loop is optimised with the JIT compiler, whereas arrayfun has not had as much optimisation.
I also agree with Jan that arrayfun can make your code much nicer (i.e. easier to read/understand) since you it is clear what function the iteration is being applied to. It would be nice if arrayfun was optimised, and even had parallel support built it (oh well).
However, sometimes arrayfun is messier. When multiple functions need to be applied, a for loop can also be easier to understand.
Categorías
Más información sobre Performance and Memory en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!