Reputation:
Say for an example of printing all the factors of a number
we know if a number is odd no even numbers can be its factor. so its code can be written as:
for(int i=1;i<n;i+=n%2==0?1:2)
print i;
or by using an third variable
t=n%2==0?1:2
for(int i=1;i<n;i+=t)
print i;
Among both of the above code which one more faster/better ?
Upvotes: 0
Views: 71
Reputation: 7970
As rule of thumb, removing computation outside a loop is a good practice. The compiler may not always optimize it (in debug builds it will not try :) ).
One has to be careful not when doing this if the condition can change within the loop. e.g. n
is not constant during the duration of the loop.
Upvotes: 1
Reputation:
Executed this peice of code in 3 different ways
public class timechk {
public static void main(String arg[]){
long startTime = System.nanoTime();
int s=0,n=999999;
for(int i=1;i<n;i++){
if(n%i==0)
s+=i;
}
long endTime = System.nanoTime();
System.out.println("Took "+(endTime - startTime) + " ns");
}
}
Output:
Took 4928321 ns
Then changed i++
to i+=n%2==0?1:2
gave
Took 5051085 ns
then used third variable:
int t=n%2==0?1:2;
for(int i=1;i<n;i+=t){
Output:
Took 2961729 ns
Upvotes: 0