With regard to Memory usage and variable instantiation which is better or is there no difference :
This
for(int i = 0; i < someValue; i++)
{
Obj foo = new Obj();
Use foo.....
}
As opposed to:
Obj foo;
for(int i = 0; i < someValue; i++)
{
foo = new Obj();
Use foo.....
}
There is no difference. Any potential difference in terms of memory usage would be optimized by the compiler.
If you compile (using
javap -c) the two examples and compare the bytecode, you’ll find that the bytecode is the same. Of course, this depends on the JVM version. But since this example is so trivial, it’s probably safe to assume that neither is more memory efficient than the other.Example 1:
Code:
Bytecode:
Example 2:
Code:
Bytecode: