jGuru Forums

Efficient use of variables in an iteration.
1 posts in topic
Flat View
TOPIC ACTIONS:

Posted By:   Marshall_Benfield
Posted On:   Wednesday, January 9, 2002 04:43 PM

I am going through a large iteration of Objects and doing calculations on the results in the iteration. Which technique is more efficient (memory/time)? Technique 1: Iterator i1 = list1.iterator(); while(i1.hasNext()) { myObject = (MyObject)i1.next(); BigDecimal value1 = myObject.getValue1(); BigDecimal value2 = myObject.getValue2(); BigDecimal value3 = value1.add(value2); myObject.setValue3(value3); } OR Technique 2: Iterator i1 = list1.iterator(); BigDecimal value1 = null; BigDecimal value2 = null; BigDecimal valu31 = null; while(i1.hasNext())    More>>

I am going through a large iteration of Objects and doing calculations on the results in the iteration.
Which technique is more efficient (memory/time)?

Technique 1:

```
Iterator i1 = list1.iterator();

while(i1.hasNext())

{

myObject = (MyObject)i1.next();

BigDecimal value1 = myObject.getValue1();

BigDecimal value2 = myObject.getValue2();

BigDecimal value3 = value1.add(value2);

myObject.setValue3(value3);

}

```

OR

Technique 2:

```
Iterator i1 = list1.iterator();

BigDecimal value1 = null;

BigDecimal value2 = null;

BigDecimal valu31 = null;

while(i1.hasNext())

{

myObject = (MyObject)i1.next();

value1 = myObject.getValue1();

value2 = myObject.getValue2();

value3 = value1.add(value2);

myObject.setValue3(value3);

}

```

This is a contrived example, but is it better to define variables used in an iteration outside the iteration or does it matter?

It seems to me that Technique 2 is more efficient, but I haven't been able to read that anywhere.

Thanks.
<<Less

Re: Efficient use of variables in an iteration.

Posted By:   Christopher_Schultz
Posted On:   Thursday, January 10, 2002 05:47 AM

This question has come up before, and I have responded the same way:

The bytecode turns out to be identical.

Java stores local variables in known locations on the stack. When you get down to the bytecode level, there is no variable declaration, only a place in the stack where that variable will be.

Since the stack is allocated once (just before the method code actually starts executing), all local variables "exist" through the entire method, whether or not they are "declared yet" in your Java source code.

Hence, you should write your code so that it is more readable (that is, probably with the declarations within the loop, since those variables are not used outside of it).

Hope that helps,

-chris