How much space does an anonymous object take?

assuming the following scenario:

void thisIsCalledManyTimes(){ // .... someObject.executeIfNecessary( new Runnable(){ void run(){ //do sth here} }); } 

how much space will an anonymous object occupy? I understand that every anonymous obj object would have a pointer to the same run implementation in its method lookup table.

+4
source share
4 answers

The source code for Runnable does not contain any fields, so an anonymous class will not take up more space than Object , with two differences. The inner class has an implicit reference to an instance of the outer class, so you will need to consider this. It will also accept copies of final variables referenced by the outer class.

+5
source

An anonymous class takes up as much space as a non-anonymous class. All objects retain a reference to the class by which they are an instance.

The only difference between an anonymous class is that it will contain a link to

  • outer class instance
  • copy of any final variables.
+4
source

All run instances actually share the same "pointer" into the method lookup table. However, the exact size of the object depends on the contents of run and ... above it. An anonymous class created by the compiler provides space for storing variables referenced by the run method, in addition to space for storing a reference to the this object of the surrounding class.

For instance,

 private String name; void thisIsCalledManyTimes(){ final int value1 = 123; final double value2 = 456.789. someObject.executeIfNecessary( new Runnable(){ void run(){ System.out.println(name); // Referenced through the enclosing "this" System.out.println(value1); // Variable will be inserted by the compiler System.out.println(value2); // Variable will be inserted by the compiler } }); } 

reserves space in the object to store value1 , value2 and this ; each instance of an anonymous object will receive a copy of these variables.

+1
source

Use a profiler to check the size of an instance of your class. It is quite small because there are no properties - it is as large as an instance of java.lang.Object. It depends on the version of the JVM.

If you need to make this more efficient, just do:

 void thisIsCalledManyTimes(){ // .... if (someObject.isItNecessary()) { someObject.execute( new Runnable(){ void run(){ //do sth here} }); } 

}

However, I will not be so worried about it.

0
source

Source: https://habr.com/ru/post/1441289/


All Articles