For loops: definition of int as local or global

Dear all,

I am creating a class, for which some methods include loops and double loops of the form:

for (int i = 0 ; i < L1 ; ++i)
{
... do_some_calculations(i,j)
}

for (int i = 0 ; i < L1 ; ++i)
{
for (int j = 0 ; j < L2 ; ++j)
{
... do_some_more_calculations(i,j)
}
}

In addition, once the code running these methods are going to be called extremely often.

I was once told that in such situation it is better to define int i, and int j as global variable in the constructor of the class. Doing so, the code would run faster as it does not need to allocate memory to i and j every time there is a loop.

Is that true ? Is it something I have to worry about ?

Best


Last edited on
It is not something you have to worry about. Do not do that.

Everything 'm about to say has nuance and discussion and edge cases and exceptions and so on. However, as a beginner, I expect what you need are broad rules-of-thumb and as you get more skilled, you can work on understanding the complexities. This is the simple verison:


Firstly, I expect a modern compiler to do a good job of optimising the code so the version without the global would run faster anyway.

Secondly, even if there was a time saving, it would be on the order of a couple of cycles. If your code is worried about a couple of cycles, messing around with globals is not the way to handle that.

Thirdly, adding globals is a bad, bad, bad thing. Globals are bad. Global state is bad. Code that makes unnecessary use of globals is bad. Bad because it becomes complex and hard to reason about and prone to bugs. Bad.
Great, that answer the question.
Thank you for the reply.
Topic archived. No new replies allowed.