5

Will there be difference in performance between anonymous functionS and normal functions? For example, any change in overhead of function calling?

Thanks and regards!

Franck Dernoncourt
  • 77,520
  • 72
  • 342
  • 501
Tim
  • 1
  • 141
  • 372
  • 590
  • A related post which may interest you (but on JavaScript): http://stackoverflow.com/questions/80802/does-use-of-anonymous-functions-affect-performance – Franck Dernoncourt Mar 14 '12 at 23:51

2 Answers2

9

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.

  • 1
    Matlab call functions by name and by function handle. By default anonymous functions are called via the second mechanism. I guess the latter is slower. However, no specific information is released by Mathworks on the matter. –  Mar 15 '12 at 01:42
0

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.

rubenvb
  • 74,642
  • 33
  • 187
  • 332