AF
HomeTagSubmit NotesAsk AnythingLoginSubscribe Us
AF
1. Feel Free to ask and submit anything on Anyforum.in and get satisfactory answer
2. Registration is not compulsory, you can directly login via google or facebook
3. Our Experts are looking for yours ?.



programming-basics: Which for loop will be faster?



a) for(int i = 0; i < 1000; i++)
{

}

b) for(int i = 1000; i > 0; i--)
{

}

programming x 153
basics x 169
Posted On : 2016-08-04 13:54:04.0
profile MOHAMMAD SALEEM BASHA - anyforum.in MOHAMMAD SALEEM BASHA
266150
up-rate
-3
down-rate

Answers


If you write blank loop, it´ll not take considerable time even in miliseconds. You can check timing by using System.currentTimeMillis() as below and i am printing the value of i to check which works faster:

ForLoop.java:
-------------------------------------------
public class ForLoop {
public static void main(String[] args) {
Long start1= System.currentTimeMillis();
for(int i = 0; i < 10000; i++)
{
System.out.println(i);
}
Long end1= System.currentTimeMillis();


Long start2= System.currentTimeMillis();
for(int j = 10000; j > 0; j--)
{
System.out.println(j);
}
Long end2= System.currentTimeMillis();

System.out.println("Time taken by first loop: "+(end1-start1));
System.out.println("Time taken by second loop: "+(end2-start2));
}
}

As if you run the program mostly cases decrement loop runs faster and it´s all happening because in bytecode comparison with 0 is a different operation than comparison with a non-zero number. Actually i < 10001 requires to first load the number on stack then execute comparison, while i > 0 is executed as one operation. In case of non-zero number CPU has to load 2 Operands to compare 2 numbers. There are special instruction to compare with 0, so only one operand must be loaded into a register.

Posted On : 2016-08-05 01:00:05
Satisfied : 2 Yes  1 No
profile Rishi Kumar - anyforum.in Rishi Kumar
523185319307
Reply This Thread
up-rate
4
down-rate



Post Answer
Please Login First to Post Answer: Login login with facebook - anyforum.in