• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Variable declaration

 
Deepak Mahbubani
Ranch Hand
Posts: 68
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 168
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Valentin Crettaz
Gold Digger
Sheriff
Posts: 7610
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Colin Kenworthy
Ranch Hand
Posts: 88
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 986
Eclipse IDE Firefox Browser Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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).]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic