Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If block vs Switch-Case block

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++

like image 342
Elpezmuerto Avatar asked Oct 13 '22 22:10

Elpezmuerto


2 Answers

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.

like image 131
Michael Goldshteyn Avatar answered Oct 27 '22 16:10

Michael Goldshteyn


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.

like image 34
Lou Franco Avatar answered Oct 27 '22 15:10

Lou Franco