Reputation: 43
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.
Upvotes: 4
Views: 960
Reputation: 141200
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();
}
Upvotes: 3
Reputation: 89192
Make foo
and fooFirst
, and then call like this
fooFirst();
for (...) {
foo();
}
foo
and fooFirst
can share code.
Upvotes: 3
Reputation: 644
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
Upvotes: 4
Reputation: 224112
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)) {
Upvotes: 6