gpt4 book ai didi

java - 请解释 Guava 代码库中 Preconditions.java 的热点优化重构?

转载 作者:行者123 更新时间:2023-12-04 20:03:16 25 4
gpt4 key购买 nike

我正在浏览 Guava 代码库和 in Preconditions source there is some explanation如下引用:

All recent hotspots (as of 2009) really like to have the natural code

if (guardExpression) {
throw new BadException(messageExpression);
}

refactored so that messageExpression is moved to a separate String-returning method.

if (guardExpression) {
throw new BadException(badMsg(...));
}

The alternative natural refactorings into void or Exception-returning methods are much slower. This is a big deal - we're talking factors of 2-8 in microbenchmarks, not just 10-20%. (This is a hotspot optimizer bug, which should be fixed, but that's a separate, big project).

The coding pattern above is heavily used in java.util, e.g. in ArrayList. There is a RangeCheckMicroBenchmark in the JDK that was used to test this.

But the methods in this class want to throw different exceptions, depending on the args, so it appears that this pattern is not directly applicable. But we can use the ridiculous, devious trick of throwing an exception in the middle of the construction of another exception. Hotspot is fine with that.

它适用于哪些 jvm?为什么它很慢,我无法理解?作为开发人员,这对我意味着什么?它是否仍然适用于 oracle 和 openjdk 的 java8 jvms?如何在编写代码时利用这条信息?

最佳答案

For which jvm(s) it is applicable?

HotSpot - Oracle 的 JVM 实现

Why it is slow, I cant understand?

这是 JVM 实现的一个特性。没有特别的原因(就 JLS/JVMS 而言)为什么它应该更慢,但截至上次有人分析它时,确实如此。您找到的 RangeCheckMicroBenchmark 类有更多详细信息和示例。

What it implies for me as developer?

没有。除非您正在实现一个像 Preconditions 这样的类——它有数百万次使用,所有这些都需要尽可能接近零开销——您没有理由担心这个细节。这就是为什么它是代码注释,而不是 Javadoc 注释。

Is it still applicable for java8 jvms by oracle and openjdk?

可能是的。该评论未链接到特定的 HotSpot 错误,但您可以在 JDK 邮件列表中搜索基准代码的提及并找到相关错误。

如果 JVM 的行为发生变化,Preconditions 很可能会更新。

How to take advantage of this piece of information while writing code?

确实没有必要这样做。如果您最终编写了 Guava 2.0,您将(希望)运行您自己的基准测试,并会发现值得以这种方式解决的瓶颈。尝试利用微优化而不对您自己的代码进行严格的基准测试可能弊大于利。

关于java - 请解释 Guava 代码库中 Preconditions.java 的热点优化重构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40487188/

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