0

Is there any performance penalties has 1st sample vs. 2nd one and why?

// 1. variable is declared inside the loop body
while(isSomethingTrue == true) {
  std::string str;
  findStr(str); // str initialization
  processStr(str); // processStr does not change its argument
}

// 2. variable is declared outside the loop body
std::string str;
while(isSomethingTrue == true) {
  findStr(str);
  processStr(str);
}
Loom
  • 9,768
  • 22
  • 60
  • 112
  • 2
    Assuming `findStr` and `precessStr` are non trivial, this is likely to be a non issue. Benchmark first, ask later. – Borgleader Nov 11 '14 at 13:19
  • 1
    Also depends on the std::string constructor, destructor and assignment operator implementation in your C++ standard library. This limits the broad applicability of the benchmark you do on your system. – pts Nov 11 '14 at 13:23

2 Answers2

3

It is a good practice to create variables inside the loop, in order to ensure their scope is restricted to that loop. Also, it is important to declare the variables as close to their are going to be used as you can.

Here is another post with more information about that:

Declaring variables inside loops, good practice or bad practice?

Community
  • 1
  • 1
  • +1 certainly true for POD, but if performance ever matters (and it does sometimes) then it's also good practice to allocate buffers outside of loop bodies – BeyelerStudios Nov 11 '14 at 13:42
1

In general there will be the overhead of running the constructor/deconstructor of your object per loop iteration, if it isn't plain old data. In case of string: allocating and deallocating str's internal buffer. This only impacts performance if findStr and processStr are both highly performant too.

BeyelerStudios
  • 4,243
  • 19
  • 38