0

Are there any performance concerns with using anonymous classes to achieve lazy evaluation of arguments in Java? It seems like each object would be created every time this code is called and then they would all be GCed afterwards.

Example:

a.func(
    new Lazy1() {
        public void func1() {
            call1();
        }
    },
    new Lazy2() {
        public void func2() {
            call2();
        }
    });

where func calls either func1 or func2 depending on some field of a.

Corey Wu
  • 1,209
  • 1
  • 22
  • 39
  • "Are there any performance concerns" is orthogonal to "each object would be created every time". The latter is certainly true; but whether it is a performance concern depends upon how this is used. – Andy Turner Mar 29 '18 at 21:51
  • 1
    This is dramatically much slower than an `if/else` statement, if that's what you mean. Whether it matters for your use case is a different question. – that other guy Mar 29 '18 at 21:52
  • 2
    Note that Java has lambda expressions since Java 8. Lazy should be a Runnable, and the two lazies should be written as lambda expressions or method references. – JB Nizet Mar 29 '18 at 21:53

1 Answers1

0

Anonymous classes hold an implicit reference to the outer class. It might have a slight effect on your performance especially when the garbages roll around, such situations that there is no point of keeping the outer class alive. You'll be collecting more garbages instead of falling the outer class out of scope when it is not needed anymore.

Ref: Java anonymous class efficiency implications

Ref2: Java8 Lambdas vs Anonymous classes

Eray Balkanli
  • 7,752
  • 11
  • 48
  • 82