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!
Aucun commentaire:
Enregistrer un commentaire