There is this a quite common question I see, should i do
Code:
for (int i = 0; i < vec.size(); ++i)
{
...
}
or
Code:
int len = vec.size();
for (int i = 0; i < len; ++i)
{
...
}
provided of course that the size of vector vec doesn't actually change in the loop and you cannot use the "for each" syntax as you want to have the counter i. I would say that you shouldn't optimize and that there are good chances the compiler will optimize anyway, but in the cases that optimization is a good choice, would you think that it is cleaner to write it instead like:
Code:
for (int len = vec.size(), i = 0, ; i < len; ++i)
{
...
}
It is a bit more cleaner for me since you typically read line by line when quickly viewing your code so this hides a bit the optimization which is desirable. It is also more to the point as you basically want to write "vec.size()" but you want to instruct the compiler to compute that once.
I just haven't really see it be coded that way so maybe it is just cleaner to me..