Slower processing of arrays in structures and pre-allocation

4 views (last 30 days)
CC
CC on 22 Nov 2021
Answered: Jan on 22 Nov 2021
I'm aware its best practice to pre-allocate large arrays to avoid growing them. Not doing so slows down execution as explained on the preallocation documentation page.
However, when an array is an element of a structure, it seems that it doesn't much matter whether preallocation is done or not. Code on arrays in structures is also significantly slower than when the array is not in a structure. I built upon the example on the preallocation doc page to illustrate:
x(1)=0;
tic
for k = 2:2000000
x(k) = x(k-1) + 5;
end
toc
clear s;
tic
x = zeros(1,2000000);
for k = 2:2000000
x(k) = x(k-1) + 5;
end
toc
s.x(1)=0;
tic
for k = 2:2000000
s.x(k) = s.x(k-1) + 5;
end
toc
clear s;
tic
s.x = zeros(1,2000000);
for k = 2:2000000
s.x(k) = s.x(k-1) + 5;
end
toc
Results in the following:
Elapsed time is 0.166783 seconds.
Elapsed time is 0.008202 seconds.
Elapsed time is 0.731128 seconds.
Elapsed time is 0.531887 seconds.
Processing the pre-allocated array (case 2) is must faster than when the array grows (case 1). The last 2, which utilized a non-preallocated and a preallocated array in a structure, take approximately the same amount of time. Both are significantly slower than their non-structure counterparts (the first two). My questions are, should arrays in structures be pre-allocated, is the lack of efficiency with pre-allocation expected for arrays in structures, and is the overall slowdown (pre-allocation or not) expected when the array is in a strucutre?
Thanks for any assistance.

Answers (1)

Jan
Jan on 22 Nov 2021
In the first example, the pre-allocation accelerates the code by about 0.15 seconds.
With using a field of a struct, the benefit is about 0.20 seconds according to the timings you have posted. So the advantage seems to be even higher for structs. Therefore I cannot confirm your opinion, that the processing in a struct is slower, when the array is pre-allocated.
That the struct methods are slower is expected: addressing the field by its name is expensive. Therefore it is cheaper to work with a shared copy:
clear s;
tic
s.x = zeros(1,2000000);
x_copy = s.x;
for k = 2:2000000
x_copy(k) = c_copy(k-1) + 5;
end
s.x = x_copy;
toc

Products


Release

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by