Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

181
Visualizações
How is a switch statement more efficient than other conditional statements when checking for multiple possible values?

i know that using a switch-case is more efficient than liniking else-if statements when checking multiple possible variable values. But what I dont know is how does it "jump" to the right value so fast. What type of function or protocol does it generally use?

Thanks.

over 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

Take a look at this, it's explained quite well there:

When compiler compiles a switch statement, it will inspect each of the case constants and create a “jump table” that it will use for selecting the path of execution depending on the value of the expression.

https://www.geeksforgeeks.org/switch-vs-else/#:~:text=A%20switch%20statement%20is%20usually,a%20set%20of%20nested%20ifs.&text=The%20compiler%20can%20do%20this,compiler%20has%20no%20such%20knowledge.

over 4 years ago · Santiago Trujillo Relatório

0

For a small number of conditions, the difference is quite small, but for many conditions you better use a switch. The reason is that when there are many values and conditions, it uses a hashtable/hashmap (a dictionary), it's a data structure with O(1) complexity of accessing the elements, to assure that all the values get the same access time. This is why switches are better than ifs when there are many conditions to check.

over 4 years ago · Santiago Trujillo Relatório

0

For posting questions like How is <A> more efficient than <B> you have to be pretty sure that it in fact is true.

I bet I can come up with some examples for which if...else if... will perform better. For example, by benefiting from branch prediction.

Also, O(1) complexity can take longer then O(n), depending on the constant cost. And n, of course.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda