1

When I use anonymous classes for small operations like filtering a collection, there is memory allocation for a new anonymous class instance or closure in Java 8.

String firstNonEmpty = Lists.find(list, new Predicate<String>(){
     public String apply(String s){ return !s.isEmpty();}
});

Should I reuse such a predicate or a closure in Java 8? Always/in a cycle/in a GC-free method?

Andrey Chaschev
  • 16,160
  • 5
  • 51
  • 68
  • 2
    Allocation of small objects like that is cheap enough that it's rarely worth worrying about. – Louis Wasserman Sep 26 '13 at 07:08
  • possible duplicate of [Efficiency of Java "Double Brace Initialization"?](http://stackoverflow.com/questions/924285/efficiency-of-java-double-brace-initialization) – assylias Sep 26 '13 at 09:12
  • May be yes in a part that it's ineffective to create an anonymous class for trivial operation. And seems very different in a part with closure efficiency. – Andrey Chaschev Sep 26 '13 at 10:02

1 Answers1

5

Creating many small objects is close to free (allocation and GC), with the caveat that GC will run more often, so there is a slight performance cost associated with it. Creating anonymous inner classes also has specific issues - this question has several answers that address that aspect.

However creating a lambda, as in:

String firstNonEmpty = Lists.find(list, (s) -> !s.isEmpty());

does not necessarily create a new object. In particular, for stateless lambdas like that one, the JVM should only create one lambda "object" and reuse it.

Community
  • 1
  • 1
assylias
  • 321,522
  • 82
  • 660
  • 783
  • Will this create a class file on disk? – Andrey Chaschev Sep 26 '13 at 10:03
  • When inspecting bytecode and generated classes, I observe that it adds a method to the existing class but does not create a new class - However the lambda call site uses invokedynamic and I'm not 100% sure about what happens at runtime. See also [this presentation](http://wiki.jvmlangsummit.com/images/7/7b/Goetz-jvmls-lambda.pdf) for more details and performance figures. – assylias Sep 26 '13 at 10:49
  • 1
    "Worst-case lambda numbers equal to inner classes, best-case numbers much better" thanks – Andrey Chaschev Sep 26 '13 at 11:11