Reputation: 9841
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.
Upvotes: 3
Views: 276
Reputation: 2699
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.
Upvotes: 10
Reputation: 24156
Case B is best. This situation explained in S.Mcconnell book - Complete Code. And you wrong with:
So which code is better in term of speed and readability.
Case B is better by other reasons.
Upvotes: 0
Reputation: 5263
You should use case B. There is not need to create an object before you need it.
Also, your compiler will not interpret largeobject a();
as the creation of an object with the default constructor, but as a function declaration. This is called "most vexing parse".
Upvotes: 2