Often you can rely on your compiler's optimizer to solve this problem for you. But not always.
So the first step is, write simple code, profile it, and see if your code is already fast enough; if the bottleneck is elsewhere, stop optimizing. Optimization effort is fungible; if can be spent on making the important code faster, and until you profile you don't know what is important.
Then use high-yield optimization techniques, like enabling vectorization, parallelizing, and using someone else's library. That can earn you 2, 30 or even 3000x speedups for really low effort. (We just swapped a manual bit of pixel fiddling with using a library with ~50 lines changed, and identical input/output went from 2 seconds to 50 ms, a 40x speedup. The pixel fiddling wasn't bad, it was just not good)
Eventually work down to what I am going to show you next; I would only go this far for stuff like per-frame per-pixel operations, code you want to run on the order of 50 million times per second or more.
auto loop=[&](auto condition1){
while(condition2){
// code
if(condition1){
// code
}
}
};
if(condition1){
loop(std::integral_constsnt<bool,true>{});
} else {
loop(std::integral_constsnt<bool,false>{});
}
what I just did was force the branch to be pre-calculated.
The trick here is that the auto condition1
variable is an integral constant, a stateless variable with a constexpr operstor bool. This gets every compiler to dead code eliminate the unreachable branch, sometimes even in debug mode.
We can then profile this against the raw version:
loop(condition1);
easily. (If you cannot profile the speed difference, you shouldn't be doing this.)
You can also use non type template parameters; a classic way to make per-pixel operation code clean and DRY and efficient is to hoist things like "is premultiplied" or "entirely opaque" to template parameter bools.
condition1
check is outside the loop.condition1
value known at compilation time?