0

So I have something like this

    int age;

    for (auto person : persons) {
        age = std::stoi(person[0]);

        /* Do other stuff with age in this loop*/
    }

Other than style, are there any performance benefits to declaring int age = std::stoi(person[0]); inside the loop?

Lord of Grok
  • 323
  • 3
  • 12
  • @NoIdeaForUsername There is no performance benefits to declare an object of the type int before the loop because neither constructor or destructor is called. – Vlad from Moscow Feb 15 '22 at 15:55
  • [this](https://stackoverflow.com/questions/8735765/variables-declared-inside-a-loop) will helps. – Mona04_ Feb 15 '22 at 15:55
  • 1
    You should keep the variables within the current scope as much as possible. – Felierix Feb 15 '22 at 15:56
  • 3
    Maybe the question you should ask yourself is "Are there any donwnsides in declaring `int const age = ...` inside the loop?" – Bob__ Feb 15 '22 at 15:56
  • There are many _benefits_ to it. The real question is why are you concerned with only _performance_ benefits. Have you profiled your application and found this function to be a hotspot? – Taekahn Feb 15 '22 at 17:08
  • The compiler's preference is to store variables in registers. Declaring variables close to where they are accessed or in subsections, allows the Compiler to better manage the usage of registers and memory. – Thomas Matthews Feb 15 '22 at 18:05

2 Answers2

4

Since you have used the age variable only inside the for loop, you may reduce its scope and declare it inside the for loop only. That way, the compiler doesn't have to remember the variable once you're done with it in the loop.

You should declare it outside the loop only if you intend to use it outside as well.

Free Space
  • 81
  • 4
3

are there any performance benefits

Because of the "as-if" rule, it's reasonable to assume that there is no performance difference between two equivalent ways of declaring the same variable.

Caleth
  • 52,200
  • 2
  • 44
  • 75