The reason behind the slowdown is the cyclic references made by the function handles to each other indirectly through the parent workspace that holds the cell array. While deleting these handles, a lot of the time is spent in resolving these cyclic references and hence the delay in the performance.
This limitation can be worked around by creating a nested function with no arguments referring to the workspace.
Below is an illustrative example:
function fnTest(N)
fprintf('% s \n','no inputs')
tic; a=cell(N,1); for k = 1:N, a{k} = @sum; end, toc;
tic; clear a; toc;
fprintf('% s \n','Anonymous function with values from the workspace')
y=1;
tic; b=cell(N,1); for k = 1:N, b{k} = @(x)sum(x,y); end, toc;
tic; clear b; toc;
fprintf('% s \n','function handle to a nested function')
y =1;
tic; c = cell(N,1); for k = 1:N, c{k} = @(x)sum2(x); end, toc;
tic; clear c; toc;
function out = sum2(x)
out = sum(x,y);
end
end
This code results in the following timings:
>> fnTest(25000)
no inputs
Elapsed time is 0.074842 seconds.
Elapsed time is 0.238302 seconds.
Anonymous function with values from the workspace
Elapsed time is 1.042215 seconds.
Elapsed time is 6.881813 seconds.
function handle to a nested function
Elapsed time is 0.995948 seconds.
Elapsed time is 0.646475 seconds.
Best Answer