Why does deleting a cell array of anonymous references with input arguments take longer than deleting the same array if the references have no input arguments in MATLAB 7.7 (R2008b)?

2 views (last 30 days)
The following code is slowing down my application considerably:
N = 25000;
tic; a=cell(N,1); for k = 1:N, a{k} = @sum; end, toc;
tic; clear a; toc;
y=1;
tic; a=cell(N,1); for k = 1:N, a{k} = @(x)sum(x,y); end, toc;
tic; clear a; toc;
While the first CLEAR took 0.4 seconds, the last CLEAR took 40 seconds on my machine:
Elapsed time is 0.232545 seconds.
Elapsed time is 0.392423 seconds.
Elapsed time is 1.775241 seconds.
Elapsed time is 40.111263 seconds.
Why does clearing references to anonymous functions with no input arguments require considerably less time than clearing references to anonymous functions with input arguments from the base workspace?

Accepted Answer

MathWorks Support Team
MathWorks Support Team on 27 Jun 2009
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;
% nested functions have access to the workspaces of all functions in
% which it is nested. In this case it means that sum2 can "see" y, but
% it will not create a reference like an anonymous function will.
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.

More Answers (0)

Products


Release

R2008b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!