Preallocation
for
and while
loops
that incrementally increase the size of a data structure each time
through the loop can adversely affect performance and memory use.
Repeatedly resizing arrays often requires MATLAB® to spend extra
time looking for larger contiguous blocks of memory, and then moving
the array into those blocks. Often, you can improve code execution
time by preallocating the maximum amount of space required for the
array.
The following code displays the amount of time needed to create
a scalar variable, x
, and then to gradually increase
the size of x
in a for
loop.
tic x = 0; for k = 2:1000000 x(k) = x(k-1) + 5; end toc
Elapsed time is 0.301528 seconds.
If you preallocate a 1-by-1,000,000 block of memory for x
and
initialize it to zero, then the code runs much faster because there
is no need to repeatedly reallocate memory for the growing data structure.
tic x = zeros(1,1000000); for k = 2:1000000 x(k) = x(k-1) + 5; end toc
Elapsed time is 0.011938 seconds.
Use the appropriate preallocation function for the kind of array you want to initialize:
zeros
for numeric arraysstrings
for string arrayscell
for cell arraystable
for table arrays
Preallocating a Nondouble Matrix
When you preallocate a block of memory to hold a matrix of some
type other than double
, avoid using the method
A = int8(zeros(100));
This statement preallocates a 100-by-100 matrix of int8
, first by creating
a full matrix of double
values, and then by converting each
element to int8
. Creating the array as int8
values saves time and memory. For example:
A = zeros(100,'int8');
Related Examples
- Reshaping and Rearranging Arrays
- Preallocate Memory for Cell Array
- Access Data Using Categorical Arrays
- Preallocate Arrays of Graphics Objects
- Create and Initialize Object Arrays