且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

我可以在 Java 代码中做什么来优化 CPU 缓存?

更新时间:2023-09-25 19:52:40

使用 Java 获得良好性能的关键是编写惯用的代码,而不是试图以智取胜 JIT 编译器.如果您编写代码以试图影响它在本机指令级别以某种方式做事,您更有可能在脚下开枪.

The key to good performance with Java is to write idiomatic code, rather than trying to outwit the JIT compiler. If you write your code to try to influence it to do things in a certain way at the native instruction level, you are more likely to shoot yourself in the foot.

这并不是说参考位置等通用原则无关紧要.他们这样做,但我认为使用数组等是性能感知、惯用代码,但不是棘手".

That isn't to say that common principles like locality of reference don't matter. They do, but I would consider the use of arrays and such to be performance-aware, idiomatic code, but not "tricky."

HotSpot 和其他优化运行时在如何为特定处理器优化代码方面非常聪明.(例如,查看此讨论.) 如果我是专家级机器语言程序员,我会编写机器语言,而不是 Java.如果我不是,那么认为我可以比专家更好地优化代码是不明智的.

HotSpot and other optimizing runtimes are extremely clever about how they optimize code for specific processors. (For an example, check out this discussion.) If I were an expert machine language programmer, I'd write machine language, not Java. And if I'm not, it would be unwise to think that I could do a better job of optimizing my code than the experts.

此外,即使您确实知道为特定 CPU 实现某些东西的***方法,Java 的美妙之处在于一次编写,随处运行.优化"Java 代码的巧妙技巧往往会使 JIT 更难识别优化机会.遵循常见习惯用法的直接代码更容易被优化器识别.因此,即使您为测试平台获得了***的 Java 代码,该代码在不同的架构上也可能表现得很糟糕,或者充其量无法利用未来 JIT 中的增强功能.

Also, even if you do know the best way to implement something for a particular CPU, the beauty of Java is write-once-run-anywhere. Clever tricks to "optimize" Java code tend to make optimization opportunities harder for the JIT to recognize. Straight-forward code that adheres to common idioms is easier for an optimizer to recognize. So even when you get the best Java code for your testbed, that code might perform horribly on a different architecture, or at best, fail to take advantages of enhancements in future JITs.

如果您想要良好的性能,请保持简单.由非常聪明的人组成的团队正在努力加快速度.

If you want good performance, keep it simple. Teams of really smart people are working to make it fast.