Tuesday, June 19, 2007

postpone variable definition as long as possible

you dont want to incur the cost of variable creation and destruction if you are not going to use it completely.
dont ignore cost of creation if their are code paths where that variable wouldnt be used.

try to delay declaration till the time value is known.
then initialize and declare in the same statement, so that the cost of default construction of object is saved.

cost analysis in a loop:
widget w ;
for ( int i=0;i < n ; i++)
w =

OR
for ( int i=0;i < n ; i++)
widget w

cost = 1 constructor + 1 destructor + n assignments
cost = n constructors + n destructors

pick whichever is better....note that second one is slightly more tight in that w isnt visible outside loop

things to remember:
postpone variable definitions as long as possible. It increases program clarity and improves program efficiency

No comments: