tags:

views:

77

answers:

3

Possible Duplicates:
Which loop has better performance? Why?
Which is optimal ?
Efficiency of Java code with primitive types

when looping, for instance:

for ( int j = 0; j < 1000; j++) {}; and I need to instantiate 1000 objects, how does it differ when I declare the object inside the loop from declaring it outside the loop ??

 for ( int j = 0; j < 1000; j++) {Object obj; obj =}   

vs

Object obj; 
 for ( int j = 0; j < 1000; j++) {obj =}

It's obvious that the object is accessible either only from the loop scope or from the scope that is surrounding it. But I don't understand the performance question, garbage collection etc.

What is the best practice ? Thank you

A: 

There's no difference. The compiler will optimize them to the very same place.

bmargulies
Not correct. Try two of them in a row and compare the bytecode.
EJP
The byte code isn't important. Its what the JIT optimizes it into in machine code that counts.
bmargulies
+4  A: 

The first form is better. Limiting the scope of a variable makes it easier for readers to understand where and how it is used.

Performance-wise, there are some small advantages to limited scope as well, which you can read about in another answer. But these concerns are secondary to code comprehension.

erickson
A: 

I've tested the issue on my machine the difference was about 2-4ms over 10000 instances, I tested all kind of stuff, like if you instantiate and assign value:

int i=0;

in compare with:

int i;
i=0;

here is the code I used for testing, of course I changed it for testing, and there is an initial balancing effect before the machine reaches optimization, you can see that in the clear once you test:

package initializer;
public final class EfficiencyTests {
private static class Stoper {
    private long initTime;
    private long executionDuration;

    public Stoper() {
    // TODO Auto-generated constructor stub
    }
    private void start() {
        initTime = System.nanoTime();
    }
    private void stop() {
        executionDuration = System.nanoTime() - initTime;
    }
    @Override
    public String toString() {
        return executionDuration + " nanos";
    }
}

private static Stoper stoper = new Stoper();

public static void main(String[] args) {
    for (int i = 0; i < 100; i++) {
        theCycleOfAForLoop(100000);
        theCycleOfAForLoopWithACallToSize(100000);
        howLongDoesItTakeToSetValueToAVariable(100000);
        howLongDoesItTakeToDefineAVariable(100000);
        System.out.println("\n");
    }
}
private static void theCycleOfAForLoop(int loops) {
    stoper.start();
    for (int i = 0; i < loops; i++);
    stoper.stop();
    System.out.println("The average duration of 10 cycles of an empty 'for' loop over " + loops + " iterations is: " + stoper.executionDuration * 10 / loops);
}
private static void theCycleOfAForLoopWithACallToSize(int loops) {
    ArrayList<Object> objects=new ArrayList<Object>();
    for (int i = 0; i < loops; i++)
        objects.add(new Object());
    stoper.start();
    for (int i = 0; i < objects.size(); i++);
    stoper.stop();
    System.out.println("The average duration of 10 cycles of an empty 'for' loop with call to size over " + loops + " iterations is: " + stoper.executionDuration * 10 / loops);

}
private static void howLongDoesItTakeToSetValueToAVariable(int loops) {
    int value = 0;
    stoper.start();
    for (int i = 0; i < loops; i++) {
        value = 2;
    }
    stoper.stop();
    System.out.println("The average duration of 10 cycles of setting a variable to a constant over " + loops + " iterations is: " + stoper.executionDuration * 10 / loops);
}
private static void howLongDoesItTakeToDefineAVariable(int loops) {
    stoper.start();
    for (int i = 0; i < loops; i++) {
        int value = 0;
    }
    stoper.stop();
    System.out.println("The average duration of 10 cycles of initializing and setting a variable to a constant over " + loops + " iterations is: " + stoper.executionDuration * 10 / loops);

}

private static void runAForLoopOnAnArrayOfObjects() {
// TODO Auto-generated method stub

}}

you can derive how long one takes if you reduce the time of the other... (if you understand what I mean)

hope this save you some time.

thing you need to understand is that I tested this things to optimize my paint update loop of my platform and it helped. Adam.

TacB0sS