Will there be difference in performance between anonymous functionS and normal functions? For example, any change in overhead of function calling?
Thanks and regards!
Will there be difference in performance between anonymous functionS and normal functions? For example, any change in overhead of function calling?
Thanks and regards!
Unfortunately, I could not find anything specific on the subject. However, anonymous functions should have additional overhead in comparison to normal functions.
You can try it out for yourself. First create the file nonanon.m
function x=nonanon(y)
x=y^2;
end
Then create a cell file with:
%% non anon
tic
for i=1:1000000
z=nonanon(i);
end
toc
%% anon
f=@(x) x^2;
tic
for i=1:1000000
z=f(i);
end
toc
enjoy, the output:
Elapsed time is 0.513759 seconds.
Elapsed time is 14.434895 seconds.
Which concludes that anonymous functions are slower.
I repeated user677656
's little test code, but a small variant using y=x*x
instead of squaring (in both the nonanon
and the anon
case):
Elapsed time is 0.517514 seconds.
Elapsed time is 0.223450 seconds.
If I instead use the y=x^2
variant, I get similar results as user677656
:
Elapsed time is 0.402366 seconds.
Elapsed time is 7.440174 seconds.
This is with Matlab 2012b. I have no idea why on earth these give different results.
I also tested y=sin(x)
which gives similar results as the x*x
case, and y=sqrt(x)
, which resulted in a slight (2.8 vs 3.9 seconds) advantage for the nonanon
case.