participate


Java Programming [Archive] - Where should you declare variables to be used within a loop ?
<<   Back to Forum  |   Give us Feedback
This topic has 4 replies on 1 page.
abhi73
Posts:10
Registered: 2/11/06
Where should you declare variables to be used within a loop ?   
Feb 11, 2006 1:34 PM

 
Which of the below three ways of declaring variables to be used within a loop is better (faster/less memory used/maintainability)?

Would the choice change if the method had other processing and other for loops needing the same variables?


CASE 1:
    public static void setMaxDate(Log[] logs, Date maxDate) {
        for (int i = 0, iLen = logs.length; i < iLen; i++) { 
           Log log = (Log) logs[i];
           Date date = log.getDate();
            if (date == null || date.compareTo(maxDate) > 0) {
                log.setDate(maxDate);
            } // end if
        } // end for
    }


CASE 2:
    public static void setMaxDate(Log[] logs, Date maxDate) {
        Date date = null;
        Log log = null;
        for (int i = 0, iLen = logs.length; i < iLen; i++) {
            log = (Log) logs[i];
            date = log.getDate();
            if (date == null || date.compareTo(maxDate) > 0) {
                log.setDate(maxDate);
            } // end if
        } // end for
    }


CASE 3:
    public static void setMaxDate(Log[] logs, Date maxDate) {
        for (int i = 0, iLen = logs.length; i < iLen; i++) {
            final Log log = (Log) logs[i];
            final Date date = log.getDate();
            if (date == null || date.compareTo(maxDate) > 0) {
                log.setDate(maxDate);
            } // end if
        } // end for
    }
 
abhi73
Posts:10
Registered: 2/11/06
Re: Where should you declare variables to be used within a loop ?   
Feb 11, 2006 1:39 PM (reply 1 of 4)  (In reply to original post )

 
Also posted to:
http://forum.java.sun.com/thread.jspa?threadID=707454
 
dcminter
Posts:9,307
Registered: 3/4/99
Re: Where should you declare variables to be used within a loop ?   
Feb 11, 2006 1:42 PM (reply 2 of 4)  (In reply to original post )

 
Which of the below three ways of declaring variables
to be used within a loop is better (faster/less
memory used/maintainability)?

The difference is completely inconsequential for the three examples you cite. For performance, profile after the fact in the extremely unlikely event that it becomes necessary. For maintainability spend the extra time on Javadoc commenting.

For larger examples the rule of thumb is to locate variables as close as is reasonably possible to the point at which they will be used. It's rarely mandated, however, for the simple reason that it's not guaranteed to enhance clarity. Sometimes a group of related variables can be initialised en block more clearly than if they are scattered through the code as they're needed.
 
abhi73
Posts:10
Registered: 2/11/06
Re: Where should you declare variables to be used within a loop ?   
Apr 6, 2006 2:11 AM (reply 3 of 4)  (In reply to #2 )

 
I have read in quite a few sites about avoiding instantiating new objects inside loops.
public class Something {
  public static void main( String as[] ) {  
    for (int i = 0; i < 10; i++) {
      Foo f = new Foo(); //Avoid this whenever you can it's really expensive
      . . . .
    }
  }
}


But they do not tell what are better alternatives if I have to declare a new object inside the loop.

Would any of the below two options be better:

A:
public class Something {
  public static void main( String as[] ) {  
    for (int i = 0; i < 10; i++) {
      final Foo f = new Foo(); 
      . . . .
    }
  }
}


B:
public class Something {
  public static void main( String as[] ) {  
    Foo f;
    for (int i = 0; i < 10; i++) {
      f = new Foo(); 
      . . . .
    }
  }
}


Thanks.
 
sjasja
Posts:3,460
Registered: 2/15/99
Re: Where should you declare variables to be used within a loop ?   
Apr 6, 2006 2:30 AM (reply 4 of 4)  (In reply to #3 )

 
Foo f = new Foo(); //Avoid this whenever you can it's really expensive

Object creation in Java (assuming Sun JDK here) is actually very fast, about ten machine instructions. So on a 2 GHz CPU you could create a (couple of) hundred million objects per second. (YMMV. Time-consuming constructors will affect timings.)

final Foo f = new Foo();
vs.
Foo f;
for (int i = 0; i < 10; i++) {
f = new Foo();

Zero difference. If you disassemble the code (javap -c) you'll notice the produced byte code is the same (minor cosmetic variations may occur due to variables being in different order but those do not affect speed).

A variable declaration doesn't "do" anything as such at runtime. At compile time the compiler collects all declared variables and creates a stack frame for them. If you have a method with one int and one pointer then the method has (assuming 32-bit pointers) 4+4=8 bytes worth of stack frame regardless of where the variable declarations occur.

Anyway, don't worry about micro-optimizations like that. Write clear maintainable code, then profile it if speed concerns arise. Use the shortest possible declaration scope not for speed but for clarity.
 
This topic has 4 replies on 1 page.
Back to Forum
 
Read the Developer Forums Code of Conduct

Click to email this message Email this Topic

Edit this Topic
  
 
 
Forums Statistics
    Users Online : 27
  • Guests : 138

About Sun forums
  • Sun Forums is a large collection of user generated discussions. It is here to help you ask questions, find answers, and participate in discussions.

    Check out our guide on Getting started with Sun Forums for a full walkthrough of how to best leverage the benefits of this community.

Powered by Jive Forums