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

247
Vistas
First function is faster when empty but when both are filled, first function is slower

Sorry, question may not be so clear. I've been interested in writing a perfect square checking function in Javascript. For the standard case, I have written the below:

for(let i = 1; i < 1000000; i++) {
    if(Math.sqrt(i) % 1 == 0) {
        // Is perfect square
    }
}

This function typically finishes in about 3ms on my PC when the if statement is empty.

Whereas the below 'optimised' function takes about 8ms:

for(let i = 1; i < 1000000; i++) {
    if(i % 10 !== 2 && i % 10 !== 3 && i % 10 !== 7 && i % 10 !== 8) {
        if(Math.sqrt(i) % 1 == 0) {
            // Is perfect square
        }
    }
}

However if I, for example, increment a counter in the respective if statements, the first function takes around 12ms but the second stays at 8ms. Both return the same counter. I just curious to why this was?

My best guess being that Javascript ignores the if statement in the first function as it's empty, whereas, because the second function has an if statement within, it doesn't ignore. However, I suspect this may not be the case. Just interested to see if anyone has any different interpretations out there!

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