I'm trying to optimise some code i've written, and was wondering when the best place to declare a variable is. A lot of the time i'll have something like this:
1 2 3 4 5 6 7 8
for (int i = 0; i < 10000; i++)
{
int j = i;
complexClass *ptr = list[i];
anotherClass class;
}
whereby i'm declaring things in the loop. Would it be faster if i declared everything outside of the loop, or is this type of thing ok?
I've googled this question, and there's so many conflicting arguments!
If the loop is the major part of a function, it makes sense to declare a variable outside it and reuse it on every iteration rather than redeclaring it each time (Do mind: depending on what it's used for, you might have to "reset" it by giving it a neutral value again). If the for loop is only a small part of the function/its environment, it might be long before the variable goes out of scope and you'll be sitting on garbage.
It also depends on the variable. If it's an int, declaring it doesn't take much time, but it doesn't waste much space either. If it's a large class, it becomes more of an issue so you'll have to take a closer look at it.
I think you can define a "scope" regardless of any loop or function though, so you could always wrap it to make sure it goes out of scope as soon as its role is played. Just make sure that reusing the variable for each iteration doesn't cause problems. A good example is a "store min/max" variable: if you want the min/max of each row of a matrix, you can either declare it between the inner and outer loops (i.e redeclared for each row), or declare it outside of the outer loop and reset it for each outer iteration.