is 'arrayfun' faster much more than 'for' loop？
165 views (last 30 days)
Walter Roberson on 9 Feb 2017
Typically arrayfun() runs more slowly, because it needs to invoke a function call each time through its internal for loop. There is still a for loop; it is just hidden.
Jan on 9 Feb 2017
Edited: Jan on 9 Feb 2017
While in all of my tests arrayfun was slower, I have collected these tests in an M-file and run it with every new Matlab release. I'm used to write the for-loop approach at first, add the arrayfun afterwards and compare the results and speed by unit-testing. Then I comment out the slower method.
This demands for an exhaustive commenting, because it is too confusing, if somebody finds commented code some years later and has no idea, why it is not used. Or imagine that the arrayfun approach is modified later, but the commented for approach is not. This will confuse a reader massively, if it is not explained clearly.
Care for optimizing the bottlenecks only. So called premature optimization can increase the debug time dramatically, such that the total program time (programming + debugging + documenting + running) might increase.
Summary: Try it.
Arjan Lampe on 6 May 2020
It seems arrayfun is much, much more slower. Or am I messing something up?
A simple (too simple?) test. Make some test function:
function m = testf(m)
%TESTF Summary of this function goes here
% Detailed explanation goes here
for c_m = 1:numel(m)
m(c_m) = sqrt(m(c_m));
>> m = rand(15)
>> tic; for ii = 1:1000000; testf(m); end; toc
Elapsed time is 1.405036 seconds.
>> tic; for ii = 1:1000000; arrayfun(@sqrt,m); end; toc
Elapsed time is 116.857802 seconds.
That is a factor 83 slower...