Array assigning performance, : vs indexes
Show older comments
MATLAB R2018a
So recently I was playing around with some code, and in one section I have a long running for loop (N = 1,000,000+ iterations). Inside the loop I am altering the values of a 2xN array one column at a time, like so:
tic;
% blah blah blah
for i = 2:N
% blah blah blah...
% a is the 2xN array
% xy is just a 2x1 column vector
a(:, i) = xy;
end
toc
This works fine and dandy; I'm seeing run times of around 0.46 - 0.48 seconds on average. But then I changed the loop to this:
tic;
% blah blah blah
for i = 2:N
% blah blah blah...
a(1, i) = xy(1);
a(2, i) = xy(2);
end
toc
And suddenly I'm seeing a slight, but still significant increase in speed (0.41 - 0.43 seconds). This seems a bit counterintuitive to me, as I was expecting these to perform pretty much the same, if not the latter being slightly slower due to the extra array call. So I'm wondering why it is that those two explicit assignments are faster than a single bulk assignment?
And with the exception of structure and readability, is it better to just always explicitly assign values like this rather than use the : syntax?
1 Comment
DGM
on 29 May 2021
I know someone else can answer this from a deeper background in the internals of how Matlab works, but it's easy enough to test it. The results might not be guaranteed to be comparable on all other versions, but it might help give a rough idea what can be expected.
With a simple loop populating a preallocated Mx1000 array with a column vector, executed 10E3 times to average the execution time, I notice a few things:
% for M = 2
A(:,n) = thiscolumnvector; % this is slowest
A(1,n) = thiscolumnvector(1); % this takes about half the time
A(2,n) = thiscolumnvector(2);
A(1,n) = thisscalarvalue; % this is even faster
A(2,n) = thatscalarvalue;
However, as M increases, the speed advantage between cases 1 and 2 diminishes rapidly, becoming roughly equal for M somewhere around 10-20. Again, that's just with my particular test case on my computer with the specific version i was running, using the particular datatype I used. Your results may vary, but it's probably safe to expect that you'll reach a point where the second case starts being the slower option.
Accepted Answer
More Answers (0)
Categories
Find more on Performance and Memory in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!