I used to call for Collections.emptyList()
, emptySet
and emptyMap
to return a reference to an immutable empty collection instead of null
from my functions. That's because I see no reasons to allocate a new empty collection instance:
private static Collection<Cheese> getCheesesOld() {
if (cheesesInStock.isEmpty()) {
return Collections.emptyList();
}
return new ArrayList<>(cheesesInStock);
}
Today I've read the following in Item 54 of Effective Java 3rd edition:
... you can avoid the allocations by returning the same immutable empty collection repeatedly, as immutable objects may be shared freely... But remember, this is an optimization, and it's seldom called for. If you think you need it, measure the performance before and after, to ensure that it's actually helping.
For me it sounds like I should avoid returning empty immutable collections until I can prove it will increase the performance. The question is: why? Are there any other drawbacks of returning immutable empty collections besides you can't mutate it and there are more code to type?
Should I change my default behavior and defensively return a copy (Item 50) of an internal list even if it is empty instead of returning already allocated Collections.emptyList()
?