Is the conditional structure "if Else" more performative than a "switch case"?

Asked

Viewed 144 times

-4

There are major differences in performance between the conditional structure if else and the switch case within a program?

  • 3

    Always good to remember that if deserves a certain care to be compared with switch. Although erroneously taught as an alternative to each other, in most languages (especially C, which is reference to many others) the nature of both is completely different. if is conditional structure, as well as Else and the ternary operator. The switch is not a conditional structure in fact. Its nature is of jumplist, it is equivalent to a goto. Which is why you need break, IF you do not want Cascade (the break makes another "drop"), which by the way is powerful when used voluntarily.

1 answer

2


Not by a long shot. It is not possible to guarantee anything because there are different ways of use, some mistaken but still possible, besides that the form of the implementation is not something specified by the language, so there is no way to guarantee which is faster even using identical situation just speaking of language, would have to observe the specific implementation that may depend on the version.

All things considered, the normal is switch be more efficient because it was created primarily to be that, at least originally it was this idea, and C adopted it first of all to be faster, and express better certain situations came from gift, was not the main one wanted to achieve.

Java "bought" this idea and in the most common implementation does, as far as I know, the same as C, which is to use a mechanism of jump table when adopting the switch and so tends to make the execution a little faster. To learn more: How the switch works behind the scenes?.

But understand that the switch will probably be used as syntax for a completely different mechanism which is the Pattern matching. Then the conversation is quite different and closer to one if the beast rather than an optimization. Then this question becomes more complicated.

All are mechanisms of selection of what to do, but the way it works is completely different.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.