Quote:
Original post by Tree Penguin
Quote:
Original post by _the_phantom_
C++ doesnt construct a varible until it is used
If that's true i really really DON'T get the speed difference between the examples i gave above.
the speed difference you gave is pretty much a non-issue anyway (3fps isnt much, it would probably be covered by the error level with timing).
I've got a copy of Effective C++ infront of me now and, Item 32 on pg 135 "Postpone varible definitions as long as possible', says
Quote:
Remember that when you define a varible of a type with a constructor or deconstructor, you incur the cost of constrution when the control reaches the variable's definitions, and you incur the cost of destruction when the variable goes out of scope. This means there is a cost associated with unused varibles, so you want to avoid them whenever you can.
now, for something like an int the cost of construction on the stack is pretty much a case of sub 1 from the stack pointer and assign the point on the stack with the value given, deconstruction is just a case of adding back 1 to the stack pointer to remove the variable from scope. This is trivial work and shouldnt really be worried about for the most part its larger objects where things really make a difference which have complex (de)constructors.
As to the speed difference between code, thats as much down to the compiler, the settings used and even how the varible is used, as anything else.
In the for-loop example given the varaible 'i' in the first block of code is allocated, assigned and then deallocated when 'i' goes out of scope at the end of the loop.
The second code block allocated 'i', enters the loop scope, runs the loop and exits leaving the 'i' allocated on the stack (until such time it goes out of scope).
While the first version does a little more work you should pretty much ALWAYS use that version to prevent scoping issues with loop varibles.
for example:
- You declare 'i' at the top of the function or just outside the first loop it is used.
- you use 'i' in that loop
- you then use 'i' for something else later on without clearing it, this could lead to a bug which could take a while to track down, where as declaring it in the scope of the for loop instead throws a compiler error and makes you fix the code there and then.
You will see alot of code which uses the second way, this is because until recently the VC++ compile was broken and didnt respect the scoping rules correctly.