DEV Community

dinhluanbmt
dinhluanbmt

Posted on

C++,use reference(&) to speed up your functions

When you pass an argument by value, a copy of the object is created.
This can be expensive in terms of both time and memory, especially for large objects.
When you pass an argument by reference, you are passing a reference to the original object rather than creating a copy of it.
for large objects (instance of struct or class) --> use reference, if you don't want to modify it use const

struct large_struct{
   int i_arr[100000];
   char c_arr[12345];
    ...
};
void function( const large_struct& ls){
  // do some works

}
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
pauljlucas profile image
Paul J. Lucas

You don't need structs that large. The general rule is any type T such that sizeof(T) > 16 (on modern 64-bit CPUs) would benefit from passing by reference.