0

I'm writing simple JS code which should print exponents of number 3 with limit of 1000. I decided to use while loop, and I am curios if I use if statement inside my while loop will it slow down the execution of the loop?

var print=0,i=0;
while(check<10000)
{
    print=Math.pow(3,i);
    if(print<1000)
      console.log(print);
    else
      break;
    i++;
}

Of course, I don't mean in this particular part of code, because this is very simple. Or maybe I should use following code:

var print=0,i=0,check=0;
while(check<10000)
{
    print=Math.pow(3,i);
    console.log(print);
    i++;
    check=Math.pow(3,i);
}

In this case 3 variables are in use. Which way is better/faster? Thanks in advance.

Ivan Pandžić
  • 363
  • 5
  • 14
  • 1
    Why not just `while (true)`? – Ja͢ck Sep 16 '14 at 22:52
  • 1
    @Ja͢ck I agree with Jack. Just do that. Even if not, using an IF statement shouldn't make a difference. Unless you're working on some super memory intensive project where every drop of mem counts. If you were though i doubt you'd be asking this :P – Ryan Brady Sep 16 '14 at 22:53
  • @Ja͢ck thought of it, but just asking for the best way. Tnx – Ivan Pandžić Sep 16 '14 at 22:57

3 Answers3

2

A loop with a break condition would work just fine and you shouldn't have to worry about performance loss; you could reduce one condition by using an infinite loop instead, though.

And in this particular case you can unwrap one iteration and make the loop condition nicer:

for (var i = 1, print = 0; print < 1000; ++i) {
    print = Math.pow(3,i);
    console.log(print);
}
Ivan Pandžić
  • 363
  • 5
  • 14
Ja͢ck
  • 170,779
  • 38
  • 263
  • 309
1

How about a for loop:

for (var j=0,k=0;j<10000;j=Math.pow(3,k),k++) console.log(j);

http://jsfiddle.net/blaird/gmjjr1q7/

Barbara Laird
  • 12,599
  • 2
  • 44
  • 57
  • It won't because i is initialized as 0(forgot to write down), and i is incremented before check. So check is always one exponent ahead of print. – Ivan Pandžić Sep 16 '14 at 23:04
1

Jack is correct in regards to the for loop, however more specifically I would not be concerned with the if statement as it won't impact performance to any noticeable degree.

Try not to be overly concerned with the number of constant functions (if statements, variable assignments etc) and focus on restricting loop usage.

For more specifics research Big O Notation.

Community
  • 1
  • 1
Paul Connolly
  • 94
  • 1
  • 2