memcpy Optimization

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

Code Generated with the memcpy OptimizationCode Generated without the memcpy Optimization
 memcpy(&C[0], &A[0], 10000U * sizeof(double));
for (i0 = 0; i0 < 10000; i0++) {
    C[i0] = A[i0];
 memcpy(&Z[0], &X[0],1000U * sizeof(double));
Z[0] = X[0];
Z[1] = X[1];
Z[2] = X[2];
...
Z[999] = X[999];

The code generator invokes the memcpy optimization if the following conditions are true:

  • The memcpy optimization is enabled.

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

To enable or disable the memcpy optimization:

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

  • In the MATLAB® Coder™ app, set Use memcpy for vector assignment to Yes or No respectively. The default value is Yes.

The default memcpy 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).

The memset optimization also uses the memcpy threshold.

More About

Was this topic helpful?