Preallocation is a valuable tool for code that requires frequent memory reallocation. However, it is best to avoid using preallocated memory for a variable that is unused or whose value is reassigned, such as when you assign it output from another function.
For example, assume a function, fetchData
, returns a
100–element row vector, and the output is assigned to a variable with
preallocated memory. The code might look like this:
myData = zeros(1,100); % preallocated vector populated with zeros
myData = fetchData();
The fetchData
function allocates memory for its output
data. Therefore, a successful call to the fetchData
function
returns a replacement for the preallocated memory. Here, the memory is allocated
twice and preallocation has no benefit.
Avoid preallocating memory to a variable that is unused or assigned to the output of another function.