Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When is an object heavy enough so as to avoid copying?

Tags:

c++

memory

Well, I believe the title is pretty straight forward. I've read many times that one should avoid copying heavy objects, and it seems pretty rational (who would want to be a memory hog?). Question is, when should an object be considered heavy? how many members?

like image 386
Misguided Avatar asked May 08 '12 18:05

Misguided


1 Answers

Any time the object you're passing is larger than the size of a pointer (typically 4 bytes on 32-bit, 8 bytes on 64-bit), then it would be more efficient to avoid copying.

Whether or not you should pass it by reference/pointer depends on how much extra work that will be, and what you'll be doing with the data. If you pass it by reference just to create a copy and modify it in your function, then you've defeated the purpose. Any time passing it as const by-reference suffices, then it's probably a good idea to do so.

However, note that most compilers are smart enough to optimize away the copying of a read-only object when your code is compiled with optimizations on. So you needn't really worry about it unless it becomes a bottleneck and you can quantitively prove it.

like image 155
Mahmoud Al-Qudsi Avatar answered Oct 12 '22 11:10

Mahmoud Al-Qudsi