This observation is not that important, because the time performance wasted on the loop statements will probably be much higher than the looping itself. But anyway, I will s
This finding has nothing to do with preallocating or not: it deals with matlab being enable or not to compute things with several cores. When you insert the colon operator within the for
statement, it tells matlab to use several cores (i.e. multithreading).
If you set matlab on one core only with feature('accel','off')
, the observed difference with doubles
vanishes. Concerning cells
, matlab does not make use of multithreading - therefore no difference can be observed (whatever the status of accel
is).
The for
loop is multithreaded when a colon is used, and only if a colon is used. The following vectors of similar length does not engage several cores:
for k = randperm(N)
for k = linspace(1,N,N)
but for k = 1:0.9999:N
is multithreaded.
One explanation can be found on this matlab's support page. It states that multi-core processing can be done when "The operations in the algorithm carried out by the function are easily partitioned into sections that can be executed concurrently.". With a colon operator, Matlab knows that for
can be partitioned.