• Post Reply Bookmark Topic Watch Topic
  • New Topic

(Im)Proper Variable Declaration and Loop Variables  RSS feed

 
Ranch Hand
Posts: 1374
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello Friends,

I have coded some of my code in below style.

1)I am reading a file line by line.
2)Splitting the line into tokens.
3)Saving each token into different variables.(Declaring variables into loop.)

Now, I code in this way because i thought the scope of the loop variables is limited to loop only so they won't be available outside the loop and hence once the loop is executed ,memory will be freed up. But after knowing little bit about Garbage Collector i come to know that this is not the case.The better way is to declare all the variables at the start of the method so they don't created at each iteration and hence save the memory.

Now,Is this the correct way? Any suggestion.
[ June 17, 2008: Message edited by: Vishal Pandya ]
 
Ranch Hand
Posts: 210
Ruby Ubuntu VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Vishal,

Are you talking about the declaration of String[] arrtokens to be inside or outside of loop? The simple answer is it is best to keep your code logically partitioned, if arrtokens is not used outside of the loop then keep it in the loop.

A few more things that you need to know:
1. In your code it doesn't matter whether if you declare the arrtokens inside or outside of the loop because that variable will take the same amount of memory..which is the size of object reference.
2. The String array object that arrtokens points to are the one kept changing with the loop. And in your sample code, currentline.split will always return new Objects..so no memory saving or reuse there.
3. Modern JVM has a lot of tuning designed to handle tons of small and short-lived objects, it is better to let the smart JVM developer to make sure it perform as best as it can. Do not do premature optimization.
 
Marshal
Posts: 56610
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Wirianto Djunaidi:
Vishal, . . .

A few more things that you need to know:
1. In your code it doesn't matter whether if you declare the arrtokens inside or outside . . .
3. Modern JVM has a lot of tuning designed to handle tons of small and short-lived objects . . .
Agree.

A rather similar query came up, I forget when, a few weeks ago and one of the Sherriffs on JavaRanch went through the bytecode, and the bytecode appeared to be identical whether the reference was declared inside the loop or before the loop.

Sorry I can't remember any more details, but you could try a little class with the read method only in, and compare the bytecode outputs.
 
Vikas Kapoor
Ranch Hand
Posts: 1374
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello Wirianto,

Thanks for your reply.
Are you talking about the declaration of String[] arrtokens to be inside or outside of loop?
Yes,I am talking about String[] arrtokens and all other variables (like customercode,orderCompany,priProductList etc...) that i have declared inside while() loop.

I understand what you that if you don't require some variable outside the loop then better to keep(declare) inside the loop but if i declare the variable inside the loop then for every line String[] arrtokens will be created,so Isn't it better to declare all the variables at the start of the method? or whatever i have done is correct. Any feedback on my code.

Yes,the scope will be more now.So there is some tradeoff between this two ways.

Hello Campee,
you could try a little class with the read method only in, and compare the bytecode outputs.


I couldn't understand you.how can i verify that variable declaration doesn't make difference using bytecode?





[ June 17, 2008: Message edited by: Vishal Pandya ]

[ June 17, 2008: Message edited by: Vishal Pandya ]
[ June 17, 2008: Message edited by: Vishal Pandya ]
 
Campbell Ritchie
Marshal
Posts: 56610
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Compile that, open its .class file with a hex editor or with the javap tool.
Then see what happens when you lose the declaration before the loop and put this in the body of the loop:
String[] strings = {"Campbell"};
 
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Vishal Pandya:
if i declare the variable inside the loop then for every line String[] arrtokens will be created


No.

The variable declaration doesn't create an array, it just reserves place on the stack for a reference to an array. And that space will actually get reused for every run through the loop, so it doesn't make any difference on where inside the method it is declared, memorywise.

What creates the array is the call to the split method. More specifically, somewhere inside the code of that method there probably is to be found a statement like "new String[someSize]", which creates the array on the heap. So how many arrays are created don't depend on how many variables you declare, but on how often that method gets called.

Last but not least, you typically shouldn't care very much about how many objects get created. Creating and garbage collecting objects isn't much a problem these days, especially when the objects are short lived. The JVM is very well optimized for this kind of work.

What you should worry about is the readability of your code. These days, development time generally is much more costly than CPU time or RAM.
 
Vikas Kapoor
Ranch Hand
Posts: 1374
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Ilja for very good explanation.
One more question,
What does happen in this case? Only one reference will be created or three different references will be created?
[ June 17, 2008: Message edited by: Vishal Pandya ]
 
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Same answer: a reference is just a reserved spot on the stack, and absolutely nothing is done at runtime to "create" one. Therefore this loop has an empty body; the Hotspot compiler is likely to optimize it away completely.
 
Vikas Kapoor
Ranch Hand
Posts: 1374
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Ernest.
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Ernest Friedman-Hill:
Same answer: a reference is just a reserved spot on the stack, and absolutely nothing is done at runtime to "create" one.


To be more precise: space for *all* local variables of a method is reserved on the stack when a method is entered, and freed when the method is finished. This should be an O(1) operation on almost any platform - that is, the time taken for this doesn't depend on the number of local variables used.
 
Ranch Hand
Posts: 94
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sorry for bumping a pretty old thread. This is exactly the point I'm trying to convince my code reviewer about.

If one of you can provide a reference to an official documentation (preferably Sun's) about JVM's behavior with respect to declaration of references within loop, it would be easier to convince my reviewer. I tried referring to this. But since it gives the finer details of implementation he keeps claiming it will create new references in each iteration.
[ December 16, 2008: Message edited by: Chandra Sekar ]
 
Campbell Ritchie
Marshal
Posts: 56610
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Try three loopsPut them in their own methods in a really tiny class (if it is more than about 20 lines long it might fall off the end of the terminal window). Compile. Inspect the bytecode using javap -c MyLittleClass. That is what somebody did back in June and said the bytecode was identical. You will have to try it for yourself and see what happens.

I have actually tried that just now and got some very slight differences:
D:\JAVAPR~1\Trivia>javap -c TinyProgram
Compiled from "TinyProgram.java"
public class TinyProgram extends java.lang.Object{
public TinyProgram();
Code:
0: aload_0
1: invokespecial #1; //Method java/lang/Object."<init>" )V
4: return

public void loop1();
Code:
0: iconst_0
1: istore_2
2: iload_2
3: bipush 10
5: if_icmpge 17
8: ldc #2; //String Campbell
10: astore_1
11: iinc 2, 1
14: goto 2
17: return

public void loop2();
Code:
0: iconst_0
1: istore_1
2: iload_1
3: bipush 10
5: if_icmpge 17
8: ldc #2; //String Campbell
10: astore_2
11: iinc 1, 1
14: goto 2
17: return

public void loop3();
Code:
0: iconst_0
1: istore_1
2: iload_1
3: bipush 10
5: if_icmpge 17
8: ldc #2; //String Campbell
10: astore_2
11: iinc 1, 1
14: goto 2
17: return

}
You will have to find a bytecode book or assembler tutorial to see what the differnce between istore_1 and istore_2 is.
[ December 16, 2008: Message edited by: Campbell Ritchie ]
 
Campbell Ritchie
Marshal
Posts: 56610
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I did a search and this is the old thread mentioned.
 
Campbell Ritchie
Marshal
Posts: 56610
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
But this thread is now beyond the scope of "beginners'". Moving.
 
Chandra Sekar
Ranch Hand
Posts: 94
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
@Campbell

I had tried that trick too. Basically unless I get some well known expert telling it, I have little chance of convincing him.

iload_<n> loads the local variable in the nth index of the local variable array of current frame.

iload_<n> and iload <n> are the same except that the operand is implicit in first case.
 
Campbell Ritchie
Marshal
Posts: 56610
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That's as far as I can go. Sorry.

Anybody else.

And you may have to come to the conclusion there are some things you just have to put up with . . .
 
Chandra Sekar
Ranch Hand
Posts: 94
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Campbell Ritchie:
And you may have to come to the conclusion there are some things you just have to put up with . . .


 
Don't get me started about those stupid light bulbs.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!