MATLAB: Performance of non-preallocated array

for loopperformancepreallocation

I'm trying to understand the reason these two options are so differnet in performance:
>> tic;z=[];for i = 1:1e5;z(end+1)=i;end;toc
Elapsed time is 0.022571 seconds.
>> tic;z=[];for i = 1:1e5;z = [z i];end;toc
Elapsed time is 7.752663 seconds.
In both we create an array of the numbers 1 to 100000 while increasing the size of the array (without pre-allocating the array) but in the second option, the concatenation is taking much more time than the isertion option, although in both cases we have to re-allocate the memory and copy the array to the new place in memory.
Thanks Noam

Best Answer

Hi,
two comments:
  • You are doing the timing in the command line. This gives typically worse results than in a function, because MATLAB can do within functions some runtime optimizations (acceleration) that is not possible on command line. If you put the code into a function, the results (for my machine) are 0.02 vs 0.10 seconds, so still quite a difference but not as drastic as in your case.
  • Second: the line "z(end+1)=i" is recognized by the accelerator as "grow in a loop without preallocation", so behind the scenes it will grow the array not simply element by element but will do some sort of preallocation itself. That's better than nothing but of course never as good as explicit preallocation.
Titus