gpt4 book ai didi

java - 返回空的不可变集合而不是分配一个新的空集合有什么缺点?

转载 作者:行者123 更新时间:2023-11-30 07:41:02 25 4
gpt4 key购买 nike

我过去常常调用 Collections.emptyList()emptySetemptyMap 来返回对不可变空集合的引用,而不是 null 来 self 的函数。那是因为我认为没有理由分配一个新的空集合实例:

private static Collection<Cheese> getCheesesOld() {
if (cheesesInStock.isEmpty()) {
return Collections.emptyList();
}
return new ArrayList<>(cheesesInStock);
}

今天我阅读了 Effective Java 第三版第 54 条中的以下内容:

... you can avoid the allocations by returning the same immutable empty collection repeatedly, as immutable objects may be shared freely... But remember, this is an optimization, and it's seldom called for. If you think you need it, measure the performance before and after, to ensure that it's actually helping.

对我来说,听起来我应该避免返回空的不可变集合,直到我能证明它会提高性能。问题是:为什么?返回不可变的空集合除了不能改变它还有更多代码要输入之外还有其他缺点吗?

我是否应该更改我的默认行为并防御性地返回一个内部列表的副本(第 50 项),即使它是空的而不是返回已分配的 Collections.emptyList()

最佳答案

Collections.emptyList()不要分配内部数组,立即知道它们的大小,可能会为它们编写更好的迭代器/拆分器(调用 .stream() 时很重要);另一方面,if分支可能比您从 Collections.emptyList() 获得的 yield 更昂贵.

这里通常的建议是 - 使用对您来说更有效和更容易阅读的任何内容。一个可能存在这种优化但实际上没有存在的地方是在 Collectors.toList() 中。 : 它总是返回一个空的 ArrayList ,而不是可能返回 Collections.emptyList()java-8 .我认为这是专门完成的,因为对这种很少使用的场景的检查会在频繁使用的场景中引入惩罚;因此没有完成。

您还必须对书中的建议持保留态度 - 那个人编写了数百万人使用的库(那里有非常好的建议),但您是否也在这样做?

关于java - 返回空的不可变集合而不是分配一个新的空集合有什么缺点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56617795/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com