The Artima Developer Community
Sponsored Link

Java Answers Forum
Creating variables on the stack

4 replies on 1 page. Most recent reply: Aug 22, 2003 3:44 AM by Dennis Benzinger

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 4 replies on 1 page
Ryan Slander

Posts: 3
Nickname: nirvana
Registered: Aug, 2003

Creating variables on the stack Posted: Aug 21, 2003 4:07 AM
Reply to this message Reply
Advertisement
Hi,

Would there be a difference between the following 2 blocks of code at runtime

Block 1
-------

boolean check;
do
{
   check = true;
   ...
   ...
   ...
   if(check)
   {
      more = false;
   }
}
while(more);


Block 2
-------

do
{
   boolean check = true;
   ...
   ...
   ...
   if (check)
   {
      more = false;
   }
}
while(more);


I prefer Block 2 because it looks more readable.

regards
Ryan


David

Posts: 150
Nickname: archangel
Registered: Jul, 2003

Re: Creating variables on the stack Posted: Aug 21, 2003 6:10 AM
Reply to this message Reply
Yeah, there is a difference, be it a small one. The second version will create a *new* boolean variable and put it on the stack frame on *each* iteration of the do...while loop. The first version only creates one.

Ryan Slander

Posts: 3
Nickname: nirvana
Registered: Aug, 2003

Re: Creating variables on the stack Posted: Aug 21, 2003 10:10 PM
Reply to this message Reply
The reason I asked this question is because it seemed quite locgial that the compiler would perform some kind of optimization by not creating multiple variables on the stack?

David

Posts: 150
Nickname: archangel
Registered: Jul, 2003

Re: Creating variables on the stack Posted: Aug 22, 2003 1:53 AM
Reply to this message Reply
Some compilers *might*, but:

1. Most of them won't.
2. You shouldn't rely on such optimisations.

I used to code very much in the style of (2), but I've now graduated to (1), factoring out the declarations to a higher level - it's more efficient and I think it's easier to read.

Dennis Benzinger

Posts: 1
Nickname: dcb
Registered: Aug, 2003

Re: Creating variables on the stack Posted: Aug 22, 2003 3:44 AM
Reply to this message Reply
There's no difference at runtime.

The second block is better programming practice as the scope of the variable check is more limited.

For more evidence that there's no difference read the following discussion on Sun's Java Programming Forum:
http://forum.java.sun.com/thread.jsp?forum=31&thread=359397

Flat View: This topic has 4 replies on 1 page
Topic: mark() and reset() Previous Topic   Next Topic Topic: memory allocation

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use