Memory consumption of anonymous classes vs. concrete subclass

Nir Lisker nlisker at gmail.com
Tue Mar 23 18:18:09 UTC 2021


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;
     }

    @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?

- Nir



More information about the valhalla-dev mailing list