Alex Rivera | Logout

Switch() { case: } performance in C

Asked 2012-09-21T12:55:28.937
10

Possible Duplicate:
Why Switch/Case and not If/Else If?

I would like to understand how a switch() case: statement in C is translated by the compiler into assembler opcodes.

Specifically, i'm interested in understanding the difference with a serie of if then else branches.

Performance comparison is the main topic.

A few words on vocabulary : i'm familiar with assembler main concepts, having coded in assembler a long time ago for simpler systems, But certainly do not now anything about x86 assembler semantic. So a direct assembler output will not be useful. Pseudo-code is much prefered.

Edit
Report

1 Answer

6

The compiler can decide to implement it as the equivalent series of if/else if statements, or it may decide to optimize it using a branch table. This depends on several parameters such as the number of branches and the size of minimum range that includes all values you check against.

Update: I remember reading somewhere that typically compilers do not bother to create a branch table unless there are at least 4 switch cases or more; Stephane Rouberol's informative comment below specifically documents how this threshold can be configured for GCC.

answered 2012-09-21T12:58:09.523

Your Answer