DEV Community

dinhluanbmt
dinhluanbmt

Posted on

1

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.

AWS Security LIVE!

Tune in for AWS Security LIVE!

Join AWS Security LIVE! for expert insights and actionable tips to protect your organization and keep security teams prepared.

Learn More

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay