vendredi 27 mai 2016

if-else styles and optimization

When you have a function whose behaviour depends on a series of conditions, you could compute it using differents if-return blocks or with a series of if-else blocks. Example computational schemas:

void f(params) // isolated if-blocks
{
    if (cond1) {
       // computational steps
       return;
    }

    if (cond2) {
       // computational steps
       return;
    }

    // computational steps of last case
 }

 void f() // unique if-else block
 {
    if (cond1) {
       // computation
    } else if (cond2) {
       // computation
    } else { // last condition
       // computation
    }
 }

I would say the first one is always more readable, but I don't know if the second one is best from a design (maintenance/error prone) or performance (branch prediction/compiler optimizations) point of view.

What are the pros and cons of both approaches? What other things have I not considered?

Aucun commentaire:

Enregistrer un commentaire