Main Content

Avoid Data Copies of Function Inputs in Generated Code

You can reduce the number of data copies in your generated code by writing MATLAB® functions that use the same variable as both an input and an output. This code pattern instructs the code generator to pass the variable by reference instead of value, which reduces the memory usage and execution time of the generated code. This code optimization is called reference parameter optimization.

Apply Reference Parameter Optimization

Define a MATLAB function foo that uses the variable A to represent both an input and the output.

function A = foo(A,B) %#codegen
A = A * B;
end

When you use a variable as both an input and output in the source MATLAB function, the code generator maps this variable to a pass-by-reference parameter in the generated C/C++ function. For example, in the code generated for foo, the input parameter A is passed by reference using a pointer:

...
/* Function Definitions */
void foo(double *A, double B)
{
    *A *= B;
}
...

This optimization avoids copying the input to a temporary variable when passing data at the call site, thereby reducing memory usage and execution time. This reduction can be especially significant when the variable passed by reference is a large data structure.

By contrast, suppose that you create a function foo2 that performs the same computation as foo but uses a new variable, y, to return the output.

function y = foo2(A,B) %#codegen
y = A * B;
end

The generated code does not use reference parameter optimization. It passes the inputs by value and returns the value of the output.

...
/* Function Definitions */
double foo2(double A, double B)
{
   return A * B;
}
...

Special Behavior for Constant Inputs

The reference parameter optimization does not apply to constant inputs. If the same variable is an input and an output, and the input is a constant, the code generator treats the output as a separate variable. For example, consider the function foo:

function A = foo(A,B) %#codegen
A = A * B;
end

Generate code in which A has a constant value 2.

codegen -config:lib foo -args {coder.Constant(2) 3} -report

The generated code elides the constant variable A, passes the nonconstant variable B by value, and returns the output by value.

...
/* Function Definitions */
double foo(double B)
{
  return 2.0 * B;
}
...

See Also

Topics