Guava ImmutableList copyOf vs Builder [英] Guava ImmutableList copyOf vs Builder

查看:481
本文介绍了Guava ImmutableList copyOf vs Builder的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道哪个更有效率,为什么?

I was wondering which is more efficient and why?

1)

List<Blah> foo;
...
return ImmutableList.copyOf(foo);

2)

List<Blah> foo;
...
return new ImmutableList.Builder<Blah>().addAll(foo).build();


推荐答案

我看不出你应该使用的任何理由这里的构建器:

I don't see any reason why you should use builder here:


  • ImmutableList.copyOf 比制作<$更具可读性c $ c> Builder 在这种情况下,

  • Builder 不会推断泛型类型,你有用作单行时用
    指定类型,

  • (来自文档) ImmutableList.copyOf 试图避免在安全的情况下实际复制数据)时,.Collection%29>做了很好的魔术

  • (来自源代码) Builder #addAll 在之前创建的<上调用 addAll code> ArrayList 而 copyOf 避免为零元素和单元素集合创建任何列表(分别返回空的不可变列表和单例不可变列表),

  • (来自源) copyOf(Collection)实例不会创建临时 ArrayList copyOf(Iterable) copyOf(Iterator)这样做),

  • (来自源代码)此外, Builder#build 在以前内部填充的 ArrayList 上调用 copyOf ,这会带给您什么问题 - 为什么要使用 Builder 这里,当你有 copyOf

  • ImmutableList.copyOf is much more readable than making a Builder in this case,
  • Builder doesn't infer generic type and you have to specify type by yourself when used as one-liner,
  • (from docs) ImmutableList.copyOf does good magic when invoked with another immutable collection (attempts to avoid actually copying the data when it is safe to do so),
  • (from source) Builder#addAll invokes addAll on previously created ArrayList while copyOf avoids creating any list for zero- and one-element collections (returns empty immutable list and singleton immutable list respectively),
  • (from source) copyOf(Collection) instance doesn't create temporary ArrayList (copyOf(Iterable) and copyOf(Iterator) does so),
  • (from source) moreover, Builder#build invokes copyOf on previously internally populated ArrayList, what brings you to your question - why use Builder here, when you have copyOf?

PS我个人使用 ImmutableList.builder()静态工厂而不是新的ImmutableList.Builder< Blah>()构造函数 - 当分配给 Builder< Blah> 变量,第一个推断泛型类型,而后者不推断。

P.S. Personally I use ImmutableList.builder() static factory instead of new ImmutableList.Builder<Blah>() constructor - when assigned to a Builder<Blah> variable the first infers generic type while the latter doesn't.

这篇关于Guava ImmutableList copyOf vs Builder的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆