Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

goto Optimization Refactor

Tags:

c++

c

goto

I have a "MyFunction" I keep obsessing over if I should or shouldn't use goto on it and in similar (hopefully rare) circumstances. So I'm trying to establish a hard-and-fast habit for this situation. To-do or not-to-do.

int MyFunction()
{   if (likely_condition)
    {
    condition_met:
        // ...
        return result;
    }
    else /*unlikely failure*/
    {   // meet condition
        goto condition_met;
    }
}

I was intending to net the benefits of the failed conditional jump instruction for the likely case. However I don't see how the compiler could know which to streamline for case probability without something like this.

  1. it works right?
  2. are the benefits worth the confusion?
  3. are there better (less verbose, more structured, more expressive) ways to enable this optimization?
like image 480
Histuries Avatar asked Dec 09 '22 20:12

Histuries


1 Answers

It appears to me that the optimization you're trying to do is mostly obsolete. Most modern processors have branch prediction built in, so (assuming it's used enough to notice) they track how often a branch is taken or not and predict whether the branch is likely to be taken or not based on its past pattern of being taken or not. In this case, speed depends primarily on how accurate that prediction is, not whether the prediction is for taken vs. not taken.

As such, you're probably best off with rather simpler code:

int MyFunction() {   
    if (!likely_condition) {
        meet_condition();
    }
    // ...
    return result;
}
like image 55
Jerry Coffin Avatar answered Dec 20 '22 20:12

Jerry Coffin