Memory consumption of anonymous classes vs. concrete subclass
    David Holmes 
    david.holmes at oracle.com
       
    Wed Mar 24 04:00:08 UTC 2021
    
    
  
Hi Nir,
On 24/03/2021 4:18 am, Nir Lisker wrote:
> Hi,
> 
> In JavaFX we have classes of the form
> 
> abstract class SomeObjectProperty {
> 
>      abstract String getName();
>      abstract Object getBean();
> }
> 
> And a concrete
> 
> class SimpleSomeObjectProperty extends SomeObjectProperty {
> 
>      String name;
>      Object bean;
> 
>      SimpleSomeObjectProperty(String name, Object bean) {
>          this.name = name;
>          this.bean = bean;
>      }
> 
>      @Override
>      abstract String getName() { return name; }
> 
>      @Override
>      abstract Object getBean() { return bean; }
> }
> 
> When we want to use a SomeObjectProperty, we usually use an
> anonymous subclass:
> 
> SomeObjectProperty prop = new  SomeObjectProperty() {
> 
>      @Override
>      public Object getBean() {
>          return ThisClass.this;
What role does ThisClass play here?
>       }
> 
>      @Override
>      public String getName() {
>          return "prop ";
>       }
> }
> 
> The reason being memory consumption. The anonymous class takes less memory
> because it holds less references. The amount varies depending on the number
> of fields and their getters (in this case we had 2, but it could be more),
> but we have done tests that show the memory footprint difference. However,
> this is much less readable obviously and much longer.
> Since JavaFX uses these properties extensively, the memory issue is
> significant and the readability issue is prominent.
> 
> I want the best of both worlds - more readable with less memory. I would
> think that under the hood something could be done to optimize this code
> since effectively it does the same. Is it possible to do something about
> this?
But the code is not effectively the same. The concrete class is a 
general class that can be instantiated multiple times for different 
beans and names - hence the fields are needed to store them. The 
anonymous class is for a singleton instance hard-wired to return one 
bean and one name. You could define a named class, specific to a given 
property, with no fields and which was also hard-wired the same way.
Cheers,
David
> - Nir
> 
    
    
More information about the valhalla-dev
mailing list