Search code examples
c++performancecoding-stylereadability

C++ Code Style - Best place to create objects


My friend and I were discussing the other day which style of code is better.

Case A:

int function()
{
    largeobject a;
    //do some stuff without a
    //do some stuff with a
}

Case B:

int function()
{
    //do some stuff without a
    largeobject a;
    //do some stuff with a
}

So which code is better in term of speed and readability.


Solution

  • You should declare variables/instances of object as locally as possible. So, in this case, B would be the best option.

    Consider that if you declare it at the top of your function body other people reading your code might wonder where you actually use the object. Therefore, by having the declaration close to where you actually use it will makes it easier to read.

    There should not be any huge performance difference between case A and B.

    There are some special cases such as allocating big chunks of memory or a thread pool for example. In these cases, since it might be time and ressources consumming you might need to find a better place to allocate them.

    If you new to programming, you might want to consider reading Scott Meyers book, Effective C++. Item 26 talks about it : Postpone variable definitions as long as possible.