So, I know that this is not a recommended method (preallocating is better), but I became very interested in this temporary behavior; I'm curious what can happen under the hood.
In my head, adding an element to an array can cause a couple of different reasonable actions in memory depending on the implementation: (1) amortized, it will take as much time to add an element as in a linked list where you keep a pointer to the last element, (2) it may now take most of the time, and then pre-allocate enough memory, for example, twice as many items as currently in the list (for example, in a Java array), (3) something smarter than I can think of.
MATLAB seems to be doing something awkward that I don't quite understand. There seems to be a linear increase in value with random spikes. Any guesses (or reasonable explanations) of what he can do? I averaged compared to simulations (which, I can imagine, might hide some interesting patterns).
This is what happens when you add one item at the end of an initially empty list iteratively. Why linear increase? Is there a good reason for seemingly periodic bursts?

The code I used to create it:
% for averaging over
num_averages = 100000;
% number of simulations
num_sims = 10000;
% the time it takes to add one more item, array
time_store = nan(num_sims, num_averages);
% averaging count
for i = 1:num_averages
% an array that grows with every loop
building_array = [];
for j = 1:num_sims
tic;
building_array = [building_array 1];
time_store(j, i) = toc;
end
end
plot(mean(time_store, 2)); hold all;
xlabel('Element num'); ylabel('Time');
source
share