Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

244
Views
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
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!