Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 509
trozen Avatar asked Oct 11 '25 20:10

trozen


1 Answers

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.

like image 112
Mureinik Avatar answered Oct 14 '25 08:10

Mureinik