Reputation: 595
Maybe this is a stupid question, but say I've got like two functions, void F1(int x) and void F2(int x), and I want to execute them in each iteration of a for loop. How much would it difer (performance-wise) if I did one big for loop, like this:
`
for(int i = 0; i < 100 ; i++)
{
F1(i);
F2(i);
}
`
compared to doing two separate loops, one in which I call F1, one in which I call F2:
`
for(int i = 0 ; i < 100 ; i++)
F1(i);
for(int i = 0 ; i < 100 ; i++)
F2(i);
`
While writing this, it occured to me that the first way is probably faster because there are only aproximately 100 increments and 100 comparisons, while in the second case, we'll get 200 of each.
Say my loop only has to run for 200 iterations. Would the two-for loops approach be pretty much the same in terms of performance, considering, say, CPUs from 2007 and after:)?
Upvotes: 1
Views: 228
Reputation: 7482
It depends on what F1
and F2
do.
It could not matter at all or you can experience dramatic slow down by having both functions called one after the other.
As an example of the latter case consider F1
and F2
accessing two different arrays. At each run of F1
and F2
they read enough data to cause the whole cache to be overwritten. That would probably cause a good slow down.
But is always better not to speculate and measure and benchmark your code instead. If performance is equivalent for both versions go for the most readable.
Upvotes: 1
Reputation: 824
Well, as you pointed out the amount of operations differ. However, if you go with the second solution you can use multiple threads and achieve the same or better performance. Also, consider readability, testability, expandability, encapsulation, usually those factors are more important than any small performance gain you might get. And also, the compiler is usually very great at making your code run more effectively, so my advice is focus on your readability more than your performance in most cases.
Upvotes: 0