为什么Guava不为小的ImmutableLists使用专门的类?(Why does Guava not use specialized classes for small ImmutableLists?)
Guava的
ImmutableList
有一系列重载of()
方法。 正如在这个解决的问题的上下文中所讨论的那样,存在这些以避免在将varargs与泛型混合时发生的警告。但除此之外,0和1参数方法都依赖于专门的列表实现。 似乎可以对2..11参数方法做同样的事情,从而减少这些列表的内存消耗 - 沿着
final class ImmutableListWith2Elements<E> extends ImmutableList<E> { final E e1; final E e2; ...
相反,它们使用基于数组的实现,这意味着除了内容引用之外,还存储数组对象和对数组的引用。 你能帮我理解这里涉及的权衡吗?
Guava's
ImmutableList
has a series of overloadedof()
methods. As discussed in the context of this solved question, these exist to avoid the warnings that occur when mixing varargs with generics.But in addition to that, the 0 and 1 parameter methods each rely on a specialized list implementation. It would seem that the same thing could be done for the 2..11 parameter methods, thereby reducing memory consumption of these lists - along the lines of
final class ImmutableListWith2Elements<E> extends ImmutableList<E> { final E e1; final E e2; ...
Instead, they use an array-based implementation, which means storing an array object and a reference to the array in addition to the content references. Can you help me understand the trade-offs involved here?
原文:https://stackoverflow.com/questions/10568440
最满意答案
你能帮我理解这里涉及的权衡吗?
这是一个权衡:
- 性能 - 不分配临时数组可以节省成本。 但是,人们需要进行一些广泛的代码分析和基准测试来量化这种节省。 (我怀疑在大多数应用程序中它都是微不足道的。请阅读@Voo提供的这个链接 !)
- 可读性 - 拥有一堆额外的重载会使javadoc混乱。
- 可维护性 - 有一堆重载是以不需要临时对象的方式实现的,这需要大量的复制/粘贴编程,这使得将来的代码维护更加困难。
- 实用程序 - 这些重载的使用频率是多少? 我希望答案“很少”。
- 字节码占用空间 - 这些额外的重载将导致使用Guava JAR文件的每个应用程序的应用程序膨胀。
我的建议:
- 不要对Guava开发人员提出这个问题。 他们已经决定了权衡取舍。 你只是在浪费你的气息。
- 如果缺少这些类或方法会损害您的应用程序,请自行添加。 (但尝试以不涉及番石榴的私人“叉子”的方式来做这件事......因为从长远来看,你可能会后悔。)
为了记录,我认为Guava开发人员做对了。
Can you help me understand the trade-offs involved here?
It is a tradeoff between:
- Performance - there is a saving from not allocating the temporary array. However, one would need to do some extensive code analysis and benchmarking to quantify that saving. (I suspect that in most applications it would be insignificant. And read this link contributed by @Voo!)
- Readability - having a bunch of the extra overloads clutters up the javadocs.
- Maintainability - having a bunch of overloads that are implemented iun such a way that the temporary object is not required would entail a lot of copy/paste programming, and this makes future code maintenance harder.
- Utility - how often would these overloads be used? I expect that the answer would be "rarely".
- Bytecode footprint - these extra overloads would contribute to application bloat for every application using the Guava JAR file.
My advice:
- Don't bug the Guava developers about this. They've already made up their minds about the tradeoffs. You'll just be wasting your breath.
- If the lack of these classes or methods hurts your application, roll your own additions. (But try to do it in a way that doesn't involve a private "fork" of Guava ... because you'll probably regret that in the long term.)
For the record, I think that the Guava developers got this right.