Sunday, September 8, 2019

c++ - Loop performance for local variable




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);
}

Answer



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.


No comments:

Post a Comment

hard drive - Leaving bad sectors in unformatted partition?

Laptop was acting really weird, and copy and seek times were really slow, so I decided to scan the hard drive surface. I have a couple hundr...