5

Generally is there a performance difference between using an if block with many else ifs compared to a switch case block? Do some languages or style conventions prefer one over the other?

Specifically I am curious about Matlab, C, and C++

Elpezmuerto
  • 5,391
  • 20
  • 65
  • 79
  • http://stackoverflow.com/questions/445067/if-vs-switch-speed – zod Oct 14 '10 at 14:51
  • http://stackoverflow.com/questions/97987/switch-vs-if-else – zod Oct 14 '10 at 14:51
  • 1
    Maybe I also should ask this kind of question, to get some rep? Who cares about duplicates... – Oleh Prypin Oct 14 '10 at 14:53
  • @BkaXpirit, this was no the intent at all. If you really care to know I asked this question quick on my mobile device so I didn't much time to browse through other questions. Nothing popped up when I entered the title when I first asked the question. Besides as of this comment, I don't think 17 rep is doing me that much – Elpezmuerto Oct 14 '10 at 22:16

2 Answers2

3

A switch can be optimized by the compiler, in some cases, into a lookup table and branch. This could be considerably faster than multiple if/else-ifs.

Michael Goldshteyn
  • 71,784
  • 24
  • 131
  • 181
1

In C, the optimizer can turn a switch into a calculated jmp, so it can be faster. This is possible because you always switch on an integer constant.

Lou Franco
  • 87,846
  • 14
  • 132
  • 192