memset Optimization

To optimize generated code that assigns a literal constant to consecutive array elements, the code generator tries to replace the code with a memset call. A memset call can be more efficient than code, such as a for-loop or multiple, consecutive element assignments.

Code Generated with the memset OptimizationCode Generated without the memset Optimization
 memset(&Y[0], 125, 100U * sizeof(signed char));
for (i = 0; i < 100; i++) {
    Y[i] = 125;
memset(&Y[0], 0, 10000U * sizeof(double));
for (i0 = 0; i0 < 10000; i0++) {
    Y[i0] = 0.0;
memset(&Z[0], 0, 1000U * sizeof(double));
Z[0] = 0.0;
Z[1] = 0.0;
Z[2] = 0.0;
...
Z[999] = 0.0;

memset Optimization for an Integer Constant

To assign an integer constant to consecutive array elements, the code generator invokes the memset optimization when the following conditions are true:

  • The constant is a literal constant. For example, X[i] = 5.

  • For a nonzero constant:

    • The type of the constant is not multiword.

    • The length in bits of the type of the constant is the same as the length in bits of the C char type that the hardware supports.

  • The number of bytes to assign is greater than or equal to the memset optimization threshold. The number of bytes to assign is the number of array elements multiplied by the number of bytes required for the C/C++ data type.

The memset optimization threshold is the same as the memcpy optimization threshold. The default threshold is 64 bytes. To change the threshold:

  • At the command line, set the code configuration object property MemcpyThreshold.

  • In the MATLAB® Coder™ app, set Memcpy threshold (bytes).

memset Optimization for Float or Double Zero

To assign a float or double 0 to consecutive array elements, the code generator invokes the memset optimization when the following conditions are true:

  • The constant is a literal constant. For example, X[i] = 0.0.

  • The memset optimization is enabled for assignment of float or double 0 to consecutive array elements.

  • The number of bytes to assign is greater than or equal to the memset optimization threshold. The number of bytes to assign is the number of array elements multiplied by the number of bytes required for the C/C++ data type.

To enable or disable the memset optimization for assignment of float or double 0 to consecutive array elements:

  • At the command line, set the code configuration object property InitFltsAndDblsToZero to true or false, respectively. The default value is true.

  • In the MATLAB Coder app, set Use memset to initialize floats and doubles to 0.0 to Yes or No respectively. The default value is Yes.

The memset optimization threshold is the same as the memcpy optimization threshold. The default threshold is 64 bytes. To change the threshold:

  • At the command line, set the code configuration object property MemcpyThreshold.

  • In the MATLAB Coder app, set Memcpy threshold (bytes).

More About

Was this topic helpful?