Repeat / Loop Avoidance

I have a hotspot code that works in a closed loop:

for (i = 0; i < big; i++) { if (condition1) { do1(); } else if (condition2) { do2(); } else { do3(); } // Shared code goes here // More shared code goes here } 

Since condition1 and condition2 are invariant, I disabled the loop to

 if (condition1) { for (i = 0; i < big; i++) { do1(); // Shared code goes here // More shared code goes here } } else if (condition 2) { for (i = 0; i < big; i++) { do2(); // Shared code goes here // More shared code goes here } } else { for (i = 0; i < big; i++) { do3(); // Shared code goes here // More shared code goes here } } 

This works much better, but I wonder if there is a smart way to do this without repeating myself?

+7
optimization c dry
source share
2 answers

Another, perhaps more effective option is to use a macro to create code for you:

 #define DO_N(name, ...) for(int i = 0; i < big; i++){name(__VA_ARGS__);/*shared code*/} if (condition1) { DO_N(do1, .../*arguments here*/) } else if (condition 2) { DO_N(do2, ...) } else { DO_N(do3, ...) } #undef DO_N 

Its ugly, but I think it does what you want and can allow embedding where there is no function pointer.

Additionally, you may find it more readable to put your shared code in a separate macro or function.

+4
source share

I think you can declare a pointer to a function and some function foo() :

 typedef void (*fp)(void); void foo(int big, fp f) { for (int i = 0; i < big; ++i) { f(); // Shared code goes here // More shared code goes her } } 

Then change the code to something like this:

 if (condition1) { foo(big, do1); } else if (condition2) { foo(big, do2); } else { foo(big, do3); } 
+3
source share

All Articles