1

A function produces large objects. What is the most efficient approach to return those objects from the function?

  • Create an object on the stack and return by value

  • Create an object on the heap, and return it wrapped in a smart pointer

I do know that in the first case if the object has a copy constructor the Named Return Value Optimization will be performed. So it should not be a big performance issue. But if there are a lot of those objects produced stack overflow may occur. What option do I choose in which situations?

Kolyunya
  • 5,973
  • 7
  • 46
  • 81
  • 1
    @P0W if you read that topic you will realize that the second option is not covered there. Also the problem of SO is not covered there. – Kolyunya Aug 28 '13 at 05:52
  • A third option could be: make your objects smaller, so you don't have to worry about SO (which could be a problem, even if you aren't returning from a function). – juanchopanza Aug 28 '13 at 06:00
  • Use smart pointer if you need to return instances of derived types, [see](http://stackoverflow.com/questions/4809120/creating-and-returning-a-big-object-from-a-function) – cpp Aug 28 '13 at 06:15
  • @Dukeling he probably meant return in a function parameter reference. – Kolyunya Aug 28 '13 at 06:17
  • I don't think Named Return Value Optimization is guaranteed to happen (I'm not aware of the standard enforcing it, but I could be wrong), though most, if not all, fairly recent compilers probably do it. – Bernhard Barker Aug 28 '13 at 06:26

1 Answers1

1

It is very unlikely that you would REALLY encounter performance issues due to returning by value. Note that NRVO that you have mentioned is just one of many things that the compiler will do to optimize your code.

Unless you have really good reason to use pointers, avoid using them. Stick to objects with automatic storage duration, follow RAII and keep your code clean. Once you create some "large" objects, be careful about the way you are passing them across your application (avoid redundant copies being created), but apart from that any additional effort spent by trying to improve the performance will most likely be just a premature optimization.

In other words: instead of thinking about "what would be the more efficient approach?" just write a code that is as correct and clean (easy to read, easy to understand) as possible -> in this case it probably means to return by value. And if you end up with solution that is not efficient enough, just then spend effort of finding out why (but in that case you'll be facing the specific problem rather than rhetorical question at least).

LihO
  • 41,190
  • 11
  • 99
  • 167