Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

116
Vistas
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 la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda