简体   繁体   English

Collections.unmodifiableList有任何性能风险吗?

[英]Is there any performance risk to Collections.unmodifiableList?

I suggested returning Collections.unmodifiableList() instead of directly returning a member variable, and my colleague is concerned that there would be a performance hit. 我建议返回Collections.unmodifiableList()而不是直接返回一个成员变量,我的同事担心会有性能损失。 Of course the best answer is to measure it, and we may do that - but I'd like to know your experiences and any references, pro or con. 当然,最好的答案是衡量它,我们可能会这样做 - 但我想知道你的经验和任何参考,赞成或反对。

No. At least, the OpenJDK implementation literally "replaces" the modification methods with UnsupportedOperationException s, the rest adds one level of indirection, which should just get optimized away by the compiler VM (and even so, one level of indirection wouldn't be costly). 不可以。至少, OpenJDK实现使用UnsupportedOperationException逐字“替换”修改方法,其余部分添加了一个间接级别,它应该被 编译器 VM优化掉(即使如此,一个级别的间接也不会昂贵)。

If you wish to return a list that cannot be modified, any performance impact would pale in comparison to the loss in correctness, I wouldn't avoid it for performance alone, and I certainly wouldn't avoid it if it's what you need. 如果你想返回一个无法修改的列表,那么与正确性的损失相比,任何性能影响都会变得苍白,我不会单独避免它的性能,如果它是你需要的话,我当然不会避免它。

If you look at the implementation you'll see that Collections.unmodifiable is just a thin wrapper around the real collection that throws an exception for all remove/add methods instead of forwarding it. 如果你看一下实现,你会发现Collections.unmodifiable只是真实集合的一个瘦包装器,它会抛出所有删除/添加方法的异常,而不是转发它。 So no there's no performance hit (the forwarding call will be inlined by the JIT). 所以没有任何性能损失(转发呼叫将由JIT内联)。

So yes you absolutely should return an unmodifiable collection instead of the original most of the times - much better coding practice. 所以是的,你绝对应该返回一个不可修改的集合,而不是大多数时候的原始集合 - 更好的编码实践。

If the JIT inlines the functions, no. 如果JIT内联函数,没有。 If it doesn't, then yes, a slight performance hit will happen, but you will likely not be able to notice it unless you're having a very tight loop. 如果没有,那么是的,会发生轻微的性能损失,但除非你的循环非常紧密否则你可能无法注意到它

It likely will inline the function, unless maybe you compile for debugging. 它可能会内联函数,除非你编译调试。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM