user2533777
user2533777

Reputation:

is it good practice to store result in an variable rather than checking it each time in an loop if condition is same all the time

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

Answers (2)

egur
egur

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

user2533777
user2533777

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

Related Questions