0

I would like to know if copying a member variable into local stack variable in each of the object's methods cause a performance hit?

class X {
   Another instanceOfAnother;

   void foo() {

      Another local = instanceOfAnother; //Would like to know if this causes a performance hit
                                         //with regards to any garbage collection
                                         //infrastructure

   }
}
Swami PR
  • 793
  • 1
  • 8
  • 15

3 Answers3

1

Object references are just values, like ints are. (I think they're the same size as ints, in fact, but don't quote me. [I don't think the JLS or VM spec says, but this answer claims they're 32 bits on 32-bit CPUs and 64 bits on 64-bit CPUs.]) Java manages local variables using the stack, and so is fairly efficient with them. If you wouldn't worry about copying int or long from variable to variable, I wouldn't worry about copying an object reference from variable to variable.

Community
  • 1
  • 1
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
1

If you're going to use (read) the instance variable often within your method, it's arguably better to copy its value to a local variable.

Reading an instance field means getting the value of this (which will also be on the stack), dereferencing it, and accessing the field of the referenced object.

Reading a local variable means looking at its corresponding entry in the local variable table, on the stack.

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
0

It doesn't really cause a performance hit, as it is not copying the actual object (located on the heap) but it copies the reference to the object, which is usually an integer or a long.

Don't worry about GC, the only thing that will change in the garbage collection process is that there is an extra reference to an object, so if you were to say: instanceOfAnother = null; while local is still pointing to the object the GC won't be able to delete the object just yet since there is still a reference (local) pointing to it.

But this is all on such a low level and small scale that you don't have to worry about doing that, unless you really need every possible performance increase you can get from your system. But in such a scenario you should perhaps look at native languages such as C++ instead of Java.

FrederikDS
  • 96
  • 7