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

115
Visualizações
Javascript time taken to check null condition in an if statement

I was just practicing a Javascript solution to a linked list problem (reverse a linked list) when I observed the following. When my code contained this snippet:

while(head!=null) {
   temp = head.next
   head.next = prev
   prev = head
   head = temp
 }

This took 96ms and some 43.6MB.

It was correct but not in even in the top 50% with respect to speed, so I randomly decided to omit the !=null part of the if statement to see what happens.

 while(head) {
   temp = head.next
   head.next = prev
   prev = head
   head = temp 
 }

To my surprise, this reduced time to 63ms and placed it faster than 96% of the solutions! Memory taken increased slightly to 44.2MB as well. But I am confused as to why this simple change caused such a drastic speed up?

If I had to guess, I would say that the second scenario merely checks if head exists, while the first scenario actually evaluates head first and then explicitly compares it to null, or something like this. Even if this is correct, I am surprised by the speed improvement. Any insight on this?

Edit: At a suggestion in the comments I also tried (head !== null), which at 64ms was definitely faster than the first scenario but same as the second!

about 4 years ago · Juan Pablo Isaza
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