I’m currently working with a big container that i need to iterater over an do lots of things. Which of the following is considered better style?
a) Big Loop:
for (container::iterator it = myContainer.begin(); it < myContainer.end(); ++it) {
// do thing a with *it
// do thing d with *it
// do thing c with *it
// do thing b with *it
}
b) Small Loops:
for (container::iterator it = myContainer.begin(); it < myContainer.end(); ++it) {
// do thing a with *it
}
for (container::iterator it = myContainer.begin(); it < myContainer.end(); ++it) {
// do thing b with *it
}
for (container::iterator it = myContainer.begin(); it < myContainer.end(); ++it) {
// do thing c with *it
}
for (container::iterator it = myContainer.begin(); it < myContainer.end(); ++it) {
// do thing d with *it
}
I find b) better to read since a) will get clunky really easy and harder to understand. But a) will run faster I think. So which of those is better style? myContainer will contain up to 10.000 elements and this procedure will have to be repeated so performance is important.
You should use the single loop. You could refactor the code contained inside the loop into separate functions.
Splitting the big loop into four smaller loops is rather inefficient, it adds superfluous operations.