Results 1 to 2 of 2
- 09-15-2010, 11:44 AM #1
Member
- Join Date
- Aug 2010
- Posts
- 35
- Rep Power
- 0
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?
- 09-15-2010, 12:02 PM #2
Moderator
- Join Date
- Apr 2009
- Posts
- 10,481
- Rep Power
- 16
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 route...you rarely if ever gain anything. Write good, maintainable code.
Similar Threads
-
loop question
By ccie007 in forum New To JavaReplies: 22Last Post: 08-15-2010, 08:29 PM -
loop performance (no problem, just investigating)
By CJSLMAN in forum New To JavaReplies: 3Last Post: 01-18-2009, 03:02 AM -
Timing array loop performance
By Java Tip in forum java.langReplies: 0Last Post: 04-14-2008, 08:43 PM -
Valid declarations
By heat84 in forum New To JavaReplies: 1Last Post: 12-22-2007, 02:29 AM -
Help with valid declarations of a float
By baltimore in forum New To JavaReplies: 1Last Post: 07-31-2007, 10:28 AM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks