Late Declaration – A Good, but costly coding guideline!


In the good old days of Structured Programming, it was required to have all the variable declarations at the top part of the function. With the advent of Object Oriented Programming, though this concept changed and the concept of late declaration came into picture.

As a good coding practice, it is recommended now that an object should be declared at the place from where it becomes alive. This is a good practice from the organization of the code perspective, but when we look at the performance aspects of this, there are some issues.

For e.g. if there is a for loop and we instantiate a vector inside it as this is the place where it becomes alive or active, there is a degradation of performance. Let’s look at the following code snippets:

int func_Unoptimized()

{

int nStart = GetTickCount();

for (int i=0;i<10000;i++)

{

std::vector abc;

abc.push_back(100);

}

int nStop = GetTickCount();

return nStop – nStart;

}

int func_Optimal()

{

int nStart = GetTickCount();

std::vector abc;

for (int i=0;i<10000;i++)

{

abc.clear();

abc.push_back(100);

}

int nStop = GetTickCount();

return nStop – nStart;

}

The two above functions were executed on an Intel (R) Pentium D CPU 3.40 GHz machine with 4 GB RAM. func_Unoptimized took 125 ms whereas func_Optimal took 47 ms, which is about 3 times faster.

Though, both these code snippets seem to do the same thing, the major difference is that in func_Unoptimized std::vector gets constructed and destructed in every single iteration of the loop, where in func_Optimal, the vector is created and destructed just once. The additional function clear() is much less costlier than the construction and destruction. Thus we get the optimal performance.

Morals of the Story

1) Late declaration is good from code organization perspective, but be aware of the performance issues.

2) Variable declarations should be moved out of the loops as far as possible for optimal performance.

Cheers!

Ram

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s