Dynamic Memory Allocation and Performance
To achieve faster execution of generated code, minimize dynamic (or run-time) memory allocation of arrays.
MATLAB® Coder™ does not provide a size for unbounded arrays in generated code. Instead, such arrays are referenced indirectly through pointers. For such arrays, memory cannot be allocated during compilation of generated code. Based on storage requirements for the arrays, memory is allocated and freed at run time as required. This run-time allocation and freeing of memory leads to slower execution of the generated code.
When Dynamic Memory Allocation Occurs
Dynamic memory allocation occurs when the code generator cannot find upper bounds for variable-size arrays. The software cannot find upper bounds when you specify the size of an array using a variable that is not a compile-time constant. An example of such a variable is an input variable (or a variable computed from an input variable).
Instances in the MATLAB code that can lead to dynamic memory allocation are:
Array initialization: You specify array size using a variable whose value is known only at run time.
After initialization of an array:
You declare the array as variable-size using
coder.varsize
without explicit upper bounds. After this declaration, you expand the array by concatenation inside a loop. The number of loop runs is known only at run time.You use a
reshape
function on the array. At least one of the size arguments to thereshape
function is known only at run time.
Minimize Dynamic Memory Allocation
When possible, minimize dynamic memory allocation because it leads to slower execution of generated code. If you know the maximum size of a variable-size array, you can avoid dynamic memory allocation. Follow these steps:
Depending on your requirements, do one of the following:
Caution
If a variable-size array in the MATLAB code does not have a maximum size, disabling dynamic memory allocation leads to a code generation error. Before disabling dynamic memory allocation, you must provide a maximum size for variable-size arrays in your MATLAB code.