Home arrow static arrow Java Programming [Archive] - Difference between initialising variables inside a loop and outside it.
Warning: Creating default object from empty value in /www/htdocs/w008deb8/wiki/components/com_staticxt/staticxt.php on line 51
Java Programming [Archive] - Difference between initialising variables inside a loop and outside it.
This topic has 3 replies on 1 page.

Posts:2
Registered: 5/31/04
Difference between initialising variables inside a loop and outside it.  
Jun 24, 2004 9:46 PM



 
What is the difference between initialising a variable, say a String, inside a loop and outside it?
Are there performance differences, memory allocation issues etc? Or is there no difference at all?

For example:
1. Outside the loop
String s = "";
while (foo)
{
s = some variable;
}

2. Inside the loop
while(foo)
{
String s = some variable;
}
 

Posts:195
Registered: 04-05-24
Re: Difference between initialising variables inside a loop and outside it.  
Jun 24, 2004 10:01 PM (reply 1 of 3)



 
Yeah, quite a bit.

If you initialise it within a loop, everytime the loop is executed, memory has to be allocated afresh for the variable.
If you initialise at the beginning, the memory allocation is done once.Hence, it definitely improves the performance of your code.
 

Posts:90
Registered: 5/26/04
Re: Difference between initialising variables inside a loop and outside it.  
Jun 24, 2004 10:43 PM (reply 2 of 3)



 
I am not sure if there will be significant difference in speed - compiler and JVM could perform some optimization for the second example so it will be just as fast as the first one.

The main difference is the scope of variables. Those defined in the loop block will not be visible outside that block.
 

Posts:1,888
Registered: 22/08/01
Re: Difference between initialising variables inside a loop and outside it.  
Jun 24, 2004 10:59 PM (reply 3 of 3)



 
.Hence, it definitely improves the performance of your code.

That only depends on the code. Modern VM like Hotspot are very good at optimizing things.

for the in the loop thing.
Its true you need to create a new Object but memory doesnt need to be reallocated always because the VM knows the previiously declared Object has become available (it went out of scope)

Generaly: dont use the outside loop because you think it might help performance: always leave micro-optimizations for the VM.
It might be faster but its not a certantiy
 
This topic has 3 replies on 1 page.