loop counters as class members? (memory usage)

Started by
10 comments, last by cozzie 10 years, 10 months ago

See http://stackoverflow.com/questions/161053/c-which-is-faster-stack-allocation-or-heap-allocation

Stack allocation is much faster since all it really does is move the stack pointer.

Since loop counters declared locally are allocated on the stack, this is your worst case scenario in terms of performance - a single pointer move (your best case will be just using a register, which your compiler may do automatically for you, or you may explicitly request with the "register" keyword).

For memory usage, and leaving aside the fact that you're getting dangerously into micro-optimization territory here, the stack will likewise be more efficient. If you declare a loop counter as a class member, then the memory used for that loop counter will always be used, even when no loops are running. Contrast with:


for (int i = 0; i < whatever; ++i)
{
}

In this case the memory is only used within the scope of the loop itself; allocation is (worst-case) just moving the stack pointer, freeing is also (worst case) just moving the stack pointer. Best case your compiler is just going to take a register for it and just not use that register for anything else within the loop, which means it's effectively totally free: no allocation, no memory usage, fast.

Direct3D has need of instancing, but we do not. We have plenty of glVertexAttrib calls.

Advertisement
Thanks, clear.
My thought on optimization was initially that some loops are used each frame and therefor the 'int' counters of the loop would take up that much memory. Not thinking about where the memory was and how quick it's gone, also not thinking about the constant needed communication and synchronization with the class members.

Also for readability I'll go for initializing the counter in the for loop alway, like mhagain showed in the example.

Crealysm game & engine development: http://www.crealysm.com

Looking for a passionate, disciplined and structured producer? PM me

This topic is closed to new replies.

Advertisement