Why should we prefer one pre-allocation approach over the other?
I have compiled three different approaches that apparently pre-allocates memory in MATLAB.
clear all clc
N = 2^28;
tStart = tic;
% Approach #1: %X = zeros(N,1);
%Approach #2: % X = ; % X(N) = 0;
%Approach #3: %X = ; %X(N, 1) = 0;
%TEST CODE %Code that uses the previous pre-allocation approaches. %for i = 1:N % % X(i) = i; % % end
tStop = toc(tStart)
Observations (All approaches equally speed up the test code.):
Approach #1: When I use this pre-allocation approach, MATLAB effectively reserves the memory, and this memory usage shows up on the Task Manager. The task manager shows MATLAB is using 2.50 GB before and after executing the test code.
Approach #2: This approach has the same behavior as approach #1.
Approach #3: When I use this pre-allocation approach, before executing the test code, the Task Manager shows MATLAB is using only about 500MB of memory, but after executing the test code it uses 2.50 GB, as seen on approach #1 and #2.
Does it mean that Approach #3 is more memory efficient than the other two approaches? It seems as if Approach #3 is pre-allocating memory, but it is not using it until required. Thanks!
This has been discussed more than once. I think Loren has discussed it in her blog.
Play games and win prizes!Learn more