a113nw
a113nw

Reputation: 1412

efficiency of if then else.... break versus if break if break

Is there an efficiency preference for one of the following control flow options for use in a loop or switch over the other?

Option 1:

switch(...){
    case 1:
        if (...) { ... }
        else if (...) { ... }
        else if (...) { ... }
        .
        .
        .
        else if (...) { ... }
        break;
    case 2:
    .
    .
    .
}

Option 2:

switch(...){
    case 1:
        if (...) { ... break; }
        if (...) { ... break; }
        .
        .
        .
        if (...) { ... break; }
    case 2:
    .
    .
    .
}

Upvotes: 3

Views: 3744

Answers (5)

S.Lott
S.Lott

Reputation: 391818

You need something that is unambiguous.

One break per case reduces ambiguity.

Multiple break buried inside if-else inside a switch is a recipe for a disaster when one of those break's get omitted.

Upvotes: 1

user436818
user436818

Reputation: 267

if possible i would recommend the switch statement

  switch (expr) {
     case c1:
        //TODO
        break;
     case c2: 
        //TODO
        break;

     . . .
     default:
        //TODO
  }

at long if else statements this will be faster...

Upvotes: 0

Bert F
Bert F

Reputation: 87503

I suppose technically option 1 for space and option 2 for speed, but any modern compiler will likely optimize the difference away and even if it didn't, the difference is likely to be minuscule. Unless you are in a severely restrictive environment where every byte or instruction cycle counts and your compiler is very simplistic, you may be better in the long run avoiding micro optimizations and code for readability and maintainability.

Upvotes: 1

user197015
user197015

Reputation:

You could double-check assembly output in particular specific cases to be sure, but I expect that any modern compiler will produce the same code most of the time.

However, I'd prefer the first form for readability, because a chain of if/else if/else blocks more clearly indicates to me (at least) that the options are mutually exclusive whereas a series of disjoint if statements implies to me that the options might not be mutually exclusive. But that's just my subjective judgement on the style.

Upvotes: 1

Charles Duffy
Charles Duffy

Reputation: 295278

No. Any sane compiler will generate to the same output (assembly, bytecode, etc). for both.

You can demonstrate this using gcc -S to generate assembly for both versions.

Upvotes: 4

Related Questions