I have a piece of code that will be executed many times (5,000+), and an if statement that will be true only the first time. I've thought of using a "FIRST" variable and compare it each time, but it just seems like a waste to check it every single time, even if I know it's not needed.
bool FIRST = true;
void foo(){
if(FIRST){
/* do something only once */
FIRST = false;
}
/* something something... */
}
I also don't know if there is some compiler optimization that does this automatically, or another way to do it; if there is, please let me know.
And yes, I know that a mere if statement isn't a big thing, but it just annoys me.
If you're using gcc, there are macros called unlikely
and likely
that can allow it to make optimizations based on a condition.
In your case the condition will only be true the first time, so you would use unlikely
:
if (unlikely(FIRST)) {
From a compiler optimization point of view, I think an if
statement is your best bet, as it will probably compile down to something like a single JNZ
, so as long as FIRST
stays true, it will be pretty optimized.
You might also want to take a look at this thread
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With