wood burning stoves 2.0*
The moose likes Beginning Java and the fly likes Variable declaration Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Variable declaration" Watch "Variable declaration" New topic
Author

Variable declaration

Deepak Mahbubani
Ranch Hand

Joined: May 12, 2001
Posts: 68
I have the following piece of code:
do {
int i = 1;
SummaryDataVO newsData = new SummaryDataVO();
// do something
} while (count-- > 0 && rs.next());

What difference does it make if I declare int i and SummaryDataVO outside the do while loop (besides the fact that they have just block scope).
I mean, does it affect performance if these variables are declared inside the do while loop.
Deepak
Michael Fitzmaurice
Ranch Hand

Joined: Aug 22, 2001
Posts: 168
Originally posted by Deepak Mahbubani:
What difference does it make if I declare int i and SummaryDataVO outside the do while loop (besides the fact that they have just block scope).
I mean, does it affect performance if these variables are declared inside the do while loop.
Deepak

What are you using these variables for? This is not clear from the code you posted.
Michael

------------------
"One good thing about music - when it hits, you feel no pain"
Bob Marley


"One good thing about music - when it hits, you feel no pain" <P>Bob Marley
Valentin Crettaz
Gold Digger
Sheriff

Joined: Aug 26, 2001
Posts: 7610
I modified a little bit your program to be able to test it, and here are my results. The code is

the output with line 1 and 2 out of the do-loop is 18442 ms.
the output with line 1 and 2 within the do-loop is 18201 ms.
As you can see, tehre is a difference of about 200 ms...
HIH

------------------
Valentin Crettaz
Sun Certified Programmer for Java 2 Platform


SCJP 5, SCJD, SCBCD, SCWCD, SCDJWS, IBM XML
[Blog] [Blogroll] [My Reviews] My Linked In
Colin Kenworthy
Ranch Hand

Joined: Aug 06, 2001
Posts: 88
When you declare variables inside the loop you are creating new objects each pass through the loop, this is extra memory and object instantiation not to mention garbage collection.
If you really do not need new objects each time then declare and construct the object outside of the loop.
William Barnes
Ranch Hand

Joined: Mar 16, 2001
Posts: 984

You might find this thread interesting as it talks about this same thing. http://www.javaranch.com/ubb/Forum33/HTML/003719.html
[This message has been edited by Cindy Glass (edited October 23, 2001).]


Please ignore post, I have no idea what I am talking about.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Variable declaration
 
Similar Threads
while loop variable???
For loop within a for loop
Can someone fix me?
Infinite looping in 'for' and 'while' loops
do while and while