Performance of non-preallocated array
Ältere Kommentare anzeigen
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
Akzeptierte Antwort
Weitere Antworten (1)
James Tursa
am 29 Apr. 2015
1 Stimme
MATLAB's parser can sometimes pre-allocate an array behind the scenes for you (even though you didn't code it that way) if it recognizes a pattern in the for loop. It appears the parser recognizes the pattern in the first case but not the second case.
1 Kommentar
Noam
am 29 Apr. 2015
Kategorien
Mehr zu Loops and Conditional Statements finden Sie in Hilfe-Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!