本文介绍了List.of(...) 或 Collections.unmodifiableList()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果你有一个 List字符串 实例,你会继续写:

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

Collections.unmodifiableList(strings)

或切换到:

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

实例化对性能(内存和运行时)的最初影响是什么?List.of 变体是否有运行时优势?

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

推荐答案

这并不是一个很好的比较,因为这些方法做不同的事情:

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

  • Collections::unmodifiable... 创建一个不可修改的视图.它不是不可变的,因为如果您更改原始的后备集合(在您的示例中为 list),它会发生变化.
  • ...::of 另一方面,创建一个不可变的副本.更改原始列表不会影响它.
  • 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.

但正确性胜过性能.你需要什么?如果您需要一个不可变的copy,请使用新方法(或 Guava 的 Immutable...,我更喜欢).如果您需要 某些东西 不可变的,请使用 unmodifiable... 并扔掉原始的(并确保它保持原样).如果您需要调用者无法编辑的视图,请使用 unmodifiable....

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....

这篇关于List.of(...) 或 Collections.unmodifiableList()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-16 14:19
查看更多