• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Question on for loop

 
Manikandan Dharmarajan
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
I have a question on for loop
I have to create an objects, String and primitive which has to be made as null ( or default values) at starting of each for loop iteration. note that these variables are not used outside the for loop.
I can do this in two ways.
1. MyClass myobj = new MyClass();
String str = "sample";
int a = 5;
for (......)
{
myobj = null;
str = null;
a = 0;
// code assign values to str, obj, a for this iteration and it must made null again for next iteration
.
.
.
.
.
}
Note that I need to take care of reinitializing every stuff to default values or null when I enter next time into the loop. Even if I forget a single variable reinitialization, that will have stale data as the scope of the variable is not within the loop
or in an other way
2) Since I dont use these variables outside the loop, part of my mind insists on keeping them within the loop. This way, the ojects and primitives live and die within the loop.
for (.....)
{
String str = null;
int a = 0;
MyClass myobj = new MyClass();
....
......
}
This seems to be an obvious,easy and sensible way particularly when these are not used outside the for loop.
But , part of my mind says that I am doing Object creation and new primitive creation everytime i enter into the loop, which I feel is an inefficient coding ( creating an object variable from the scratch each time ) .

-------------------------------
Question is
a) whether there is any significant difference in both ways ?
b) Is the second way inefficient or is it the right way to do it?
c) Are there any performance issues related to both ways
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Performance should not be an issue. Write code for humans to read first, computers to run second. I agree the second syntax says what you are doing better. Putting the variable scope explicitly inside the loop is a good thing to help document what you meant to do and prevent mistakes using the variables outside the loop.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic