Game Development Community

for loop question in engine code

by Wendell Brown · in Torque Game Engine · 05/01/2002 (8:38 am) · 2 replies

Can someone tell me if my thinking is correct. I noticed while debugging the code that there are a lot of for loops that re-calculate the size() function during each loop iteration.
ie
c:\MYTORQUE\ENGINE\ts\tsAnimate.cc(614): for (i=0; i c:\MYTORQUE\ENGINE\ts\tsAnimate.cc(626): for (i=0; i c:\MYTORQUE\ENGINE\ts\tsAnimate.cc(674): for (i=0; i c:\MYTORQUE\ENGINE\ts\tsAnimate.cc(686): for (i=0; i c:\MYTORQUE\ENGINE\ts\tsAnimate.cc(728): for (i=0; i c:\MYTORQUE\ENGINE\ts\tsAnimate.cc(740): for (i=0; i c:\MYTORQUE\ENGINE\ts\tsAnimate.cc(782): for (i=0; i c:\MYTORQUE\ENGINE\ts\tsAnimate.cc(794): for (i=0; i c:\MYTORQUE\ENGINE\ts\tsAnimate.cc(876): for (S32 i=0; isubShapeNumNodes.size(); i++)

Is it done this way to allow object deletions by other methods that would possibly modify this size() return value? If so isn't that dangerous if the value can be dynamic like that and possible still used after the fact if it has changed but the code isn't aware of it?
I wanted to change the loop to pre-initialise another S32 temp variable to hold the size and just use it but I wanted to check if this was possible first.
My belief is that objects come and go as needed and that it was done that way to try and keep up with those additions/removals of objects.
If it can change to the pre-initializer, it would seem that we could trim some execution loop time off of these for loops.
Anyone care to edumacate me?

#1
05/03/2002 (6:00 am)
bump
#2
05/06/2002 (9:36 am)
couple of things. Using size in the for loop would not prevent a disaster if another process was to remove items while you iterated through. so it could increment past size() if size were to get a few items smaller while you were processing, however it would fail the check or < size and kick out of the loop the next time around.

note: this is bad
i = 2 size = 4
...
in loop, size changes to 1
i gets incremented at end of for loop
i = 3
i < size (nope, kicks out)

if this were with iterators it would go boom :)
*iter = something in the list
list changes while in the loop
*iter++
blows up because the list has changed

Definately not the best way to prevent that type of problem.

However in this case, its a torque vector, and it keeps track of the elements, so size, in this case doesnt do any recalculations, it just hands back the element size. So it really doesnt have much overhead at all.

For info on removing items while iterating through a list
check out a scott myers book effective stl: 50 ways to improve...
here is the amazon link
http://www.amazon.com/exec/obidos/ASIN/0201749629/ref=pd_sim_books/104-3658727-4483967