Switch v If statement

  • Thread starter Thread starter Alvin Bruney
  • Start date Start date
A

Alvin Bruney

Is a switch more efficient than an if statement? I observe thru the debugger
that a switch statement jumps directly to its case handler where as an if
statement examines all conditions sequentially. Is that a trick of the
debugger or is a switch quicker by O(n).
 
Alvin Bruney said:
Is a switch more efficient than an if statement? I observe thru the debugger
that a switch statement jumps directly to its case handler where as an if
statement examines all conditions sequentially. Is that a trick of the
debugger or is a switch quicker by O(n).

No trick. The switch statement is basically a direct jump to one of many
targets using the content of an internal table and an index computed from
the switch expression. An if ... elseif ... elseif ... statement chain is
slower. However such a chain allows for complex composite conditions that
would be very difficult or impossible to handle using a switch statement.
 
I really wish C# allowed variables in the case; i.e. "case firstName". It
can optimize 'constant' case statements, but variables would be very nice.

Hilton
 
also confusing as hell.


Hilton said:
I really wish C# allowed variables in the case; i.e. "case firstName". It
can optimize 'constant' case statements, but variables would be very nice.

Hilton
 
You think a bunch of "if" statements make things clearer? Different views I
guess. I just view the "case" as a neat way of bundling up "if"
statements...

Hilton
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top