MATLAB Examples

size() Vs. length() Vs. Stored Length in for Loop

This script compares using the functions size, length, and storing the value of an array before entering a for loop. This is important because of the time wasted calling size() or length() in a for loop versuses the clarity and quickness of coding by not storing the array size before the for loop.

By Jason Nicholson
2014-October-06 10:38:14
Version 1.0

Contents

Constants

MAX_ARRAY_LENGTH = 1e6;
NUMBER_OF_ITERATIONS = 1e7;
array = rand(1, int32(rand()*MAX_ARRAY_LENGTH));

Analyze Storing Value before Entering for Loop

arrayLength = size(array,2);
tic;
for i=1:NUMBER_OF_ITERATIONS
   arrayLength;
end
toc;
Elapsed time is  0.205824 seconds.

Analyze Calling size() Inside for Loop

tic;
for i=1:NUMBER_OF_ITERATIONS
   size(array,2);
end
toc
Elapsed time is  4.509939 seconds.

Analyze Calling length() Inside for Loop

tic;
for i=1:NUMBER_OF_ITERATIONS
   length(array);
end
toc;
Elapsed time is  3.459530 seconds.

Conclusion

Storing the value is about 17 times and 22 times faster than using length() and size() in a for loop respectively.

I tried several other arrangements of the code with the same results as shown here. Note, that if you run publish on this code, it is much slower than just running the code. I cannot explain this.