Results 1 to 2 of 2
  1. #1
    XmisterIS is offline Member
    Join Date
    Aug 2010
    Rep Power

    Default In-loop declarations and performance question ...

    Consider the following two code snippets in which vect is a vector of objects of type Thing.

    Snippet 1:
    Java Code:
    for (Enumeration<Thing> en = vect.elements(); en.hasMoreElements(); )
      Thing item = en.nextElement();
      //Rest of code here.

    Snippet 2:
    Java Code:
    Thing item;
    for (Enumeration<Thing> en = vect.elements(); en.hasMoreElements(); )
      item = en.nextElement();
      //Rest of code here.

    In the case of Snippet 1, is there any extra overhead associated with placing the declaration of item in the loop rather than outside, as in Snippet 2? Or is there no difference?

  2. #2
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Rep Power


    The former is the preferable way of doing this assuming you have no need for the final Thing object outside of the loop. The basic "rule" is to keep things in the scope in which they're needed, and no more.

    As for performance? Unless you actually have a performance issue with the code do not worry about it. Do not go down the premature optimisation rarely if ever gain anything. Write good, maintainable code.

Similar Threads

  1. loop question
    By ccie007 in forum New To Java
    Replies: 22
    Last Post: 08-15-2010, 08:29 PM
  2. loop performance (no problem, just investigating)
    By CJSLMAN in forum New To Java
    Replies: 3
    Last Post: 01-18-2009, 04:02 AM
  3. Timing array loop performance
    By Java Tip in forum java.lang
    Replies: 0
    Last Post: 04-14-2008, 08:43 PM
  4. Valid declarations
    By heat84 in forum New To Java
    Replies: 1
    Last Post: 12-22-2007, 03:29 AM
  5. Help with valid declarations of a float
    By baltimore in forum New To Java
    Replies: 1
    Last Post: 07-31-2007, 10:28 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts