Is it recommended to cache Collections.unmodifiableList() result in a field?

  • A+
Category:Languages

Which one is the recommended approach:

private final List<Object> list = new ArrayList<>();  public List<Object> getListView() {     return Collections.unmodifiableList(list); } 

or

private final List<Object> list = new ArrayList<>(); private final List<Object> listView = Collections.unmodifiableList(list);  public List<Object> getListView() {     return listView; } 

The latter saves on object creation, but is it worth the effort?

 


Creating an unmodifiableList is an O(1) operation (essentially, it instantiates a java.util.Collections$UnmodifiableList and assings your list to a datamember).

Unless you have a very convincing benchmark of your special-case that shows the contrary, it probably just isn't worth the hassle of caching it.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: