Does it make a difference if I declare variables inside or outside a loop in Java?
Posted
by
Puckl
on Programmers
See other posts from Programmers
or by Puckl
Published on 2012-10-08T09:29:20Z
Indexed on
2012/10/08
9:46 UTC
Read the original article
Hit count: 223
Does it make a difference if I declare variables inside or outside a loop in Java?
Is this
for(int i = 0; i < 1000; i++) {
int temporaryValue = someMethod();
list.add(temporaryValue)
}
equal to this (with respect to memory usage)?
int temporaryValue = 0;
for(int i = 0; i < 1000; i++) {
temporaryValue = someMethod();
list.add(temporaryValue)
}
And what if the temporary variable is for example an ArrayList?
for(int i = 0; i < 1000; i++) {
ArrayList<Integer> array = new ArrayList<Integer>();
fillArray(array);
// do something with the array
}
© Programmers or respective owner