4

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.

4 Answers4

6

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)) {
dbush
  • 205,898
  • 23
  • 218
  • 273
  • in this case we still need set FIRST to the false? Can't get it how this works ... – Nick S Jul 30 '20 at 23:55
  • @NickS The rest of the code doesn't change. All this does is tell the compiler the condition will be false most of the time and to optimize for that case. – dbush Jul 30 '20 at 23:58
4

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

tripathiakshit
  • 624
  • 5
  • 17
3

Make foo and fooFirst, and then call like this

fooFirst();
for (...) {
   foo();
}

foo and fooFirst can share code.

Lou Franco
  • 87,846
  • 14
  • 132
  • 192
3

You can call the function via a function pointer and remove the if check on the second call by changing the function pointer to a function without the if:

void foo_init(void);
void foo_real(void);    
void (*foo)(void) = foo_init;

void foo_init(void) {
   foo = foo_real;
   /* do something only once */
   foo_real();
}

void foo_real(void) {
   /* something something... */
}

int main() { 
    foo();
    foo();
}
KamilCuk
  • 120,984
  • 8
  • 59
  • 111
  • 1
    Why do you need the test? The function only gets called when `foo == foo_init` – Barmar Jul 31 '20 at 00:03
  • Och right, so it could be just removed. I think I was thinking to make the function thread-safe - then a mutex in the function body + check `if (foo == foo_init)` is needed. – KamilCuk Jul 31 '20 at 00:03