List.of(...) or Collections.unmodifiableList()

Sormuras :

If you have a List<String> strings instance, would you keep writing:

Collections.unmodifiableList(strings)

or switch to:

List.of(strings.toArray(new String[strings.size()]))

What's the initial impact in performance (memory- and runtime-wise) of instantion? Is there a runtime benefit in the List.of variant?

Nicolai :

This is not really a good comparison because these approaches do different things:

  • Collections::unmodifiable... creates an unmodifiable view. It is not immutable because it changes if you're changing the original, backing collection (list in your example).
  • ...::of on the other hand, creates an immutable copy. Changing the original list will not affect it.

From a performance view it is obvious that creation of the unmodifiable wrapper is cheaper because it only creates one instance with a single field. The new factory methods will create at least one object, maybe backed by an array (if you have three or more elements), that it needs to copy into.

Access could be faster on the new immutable collections but that would have to be benchmarked.

But correctness trumps performance. What do you need? If you need an immutable copy, use the new methods (or Guava's Immutable..., which I would prefer). If you need something immutable, use unmodifiable... and throw away the original (and make sure it stays like that). If you need a view that your caller can not edit, use unmodifiable....

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=456433&siteId=1