Reputation: 16496
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?
Upvotes: 1
Views: 689
Reputation: 328619
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.
Upvotes: 5