jGuru Forums

What is the performance difference between the following loops?
1 posts in topic
Flat View
TOPIC ACTIONS:

Posted By:   Ashwin_Joshi
Posted On:   Monday, August 6, 2001 10:55 AM

What is the performance difference between the following loops? a) for (int i=0;i < 0;i++) { int a = i; Integer b = new Integer(i); } b) int a; Integer b; for (int i=0;i < 0;i++) { a = i; b = new Integer(i); } Does location of declaration matter? The only difference in (b) is that local variables used in a loop are declared once outside the loop. Thanks    More>>

What is the performance difference between the following loops?

a)

for (int i=0;i < 0;i++)

{

int a = i;

Integer b = new Integer(i);

}

b)

int a;

Integer b;

for (int i=0;i < 0;i++)

{

a = i;

b = new Integer(i);

}

Does location of declaration matter?

The only difference in (b)
is that local variables used in a loop are declared once outside the
loop.

Thanks

<<Less

Re: What is the performance difference between the following loops?

Posted By:   Noah_Nordrum
Posted On:   Monday, August 6, 2001 11:28 AM

Consider the following test class:

`public class LoopTest {	public static final int LOOP_LENGTH = 100000000;	public static long insideLoop() {		long startTime = System.currentTimeMillis();		for (int i = 0; i < LOOP_LENGTH; i++) {			int a = i;			Integer b = new Integer(i);		}		return System.currentTimeMillis() - startTime;	}	public static long outsideLoop() {		long startTime = System.currentTimeMillis();		int a;		Integer b = null;		for (int i = 0; i < LOOP_LENGTH; i++) {			a = i;			b = new Integer(i);		}		return System.currentTimeMillis() - startTime;	}	public static void main(String args[]) {		System.out.println("Inside loop:  " + insideLoop() + "ms.");		System.out.println("Outside loop: " + outsideLoop() + "ms.");	}}`

results in:

`Inside loop:  19368ms.Outside loop: 22983ms.`

I'd say it matters ;)

Noah