java - 为什么字节码可能比 native 代码运行得更快

标签 java performance jvm native-code

<分区>

Java 很慢。

这不仅仅是一个“都市传说”,它似乎是一个事实。由于延迟,您不会将其用于实时编码,也不会将其用于集群/并行计算。那里有数以千计的基准测试,特别是“Java vs C# vs C++”。

http://benchmarksgame.alioth.debian.org/

根据上述网站,不仅 Java 的性能几乎与 C 一样好(与其他语言相去甚远),而且 Scala 和 Clojure(这两种在 JVM 上运行的函数式语言)都具有比 OCaml、Erlang 更好的性能。

还有很多“Java 比 X 快”的说法(例如,这里有一个关于 SO 的问题:Java Runtime Performance Vs Native C / C++ Code?)。

所以在某些情况下,Java 似乎很快。谁能解释一下为什么?

在某些情况下,给定动态代码(Scala、Clojure)和垃圾回收,为什么字节码可能比本地代码运行得更快?怎么再快了,还有延迟?

这似乎是一个矛盾,谁能解释一下?

最佳答案

在编程大师一书中,James Gosling 解释道:

James: Exactly. These days we’re beating the really good C and C++ compilers pretty much always. When you go to the dynamic compiler, you get two advantages when the compiler’s running right at the last moment. One is you know exactly what chipset you’re running on. So many times when people are compiling a piece of C code, they have to compile it to run on kind of the generic x86 architecture. Almost none of the binaries you get are particularly well tuned for any of them. You download the latest copy of Mozilla,and it’ll run on pretty much any Intel architecture CPU. There’s pretty much one Linux binary. It’s pretty generic, and it’s compiled with GCC, which is not a very good C compiler.

When HotSpot runs, it knows exactly what chipset you’re running on. It knows exactly how the cache works. It knows exactly how the memory hierarchy works. It knows exactly how all the pipeline interlocks work in the CPU. It knows what instruction set extensions this chip has got. It optimizes for precisely what machine you’re on. Then the other half of it is that it actually sees the application as it’s running. It’s able to have statistics that know which things are important. It’s able to inline things that a C compiler could never do. The kind of stuff that gets inlined in the Java world is pretty amazing. Then you tack onto that the way the storage management works with the modern garbage collectors. With a modern garbage collector, storage allocation is extremely fast.

关于java - 为什么字节码可能比 native 代码运行得更快,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5641356/

相关文章:

sql - 阅读 Oracle 解释计划

python - 如何加快 Pandas 中每个 groupby 组的缺失值替换?

java - 访问变量时线程行为的差异

java - Quarkus MySQL JDBC 依赖项

java - 基于输入的不同 validator

asp.net - 减少 ASP.NET 中 ViewState 大小的策略

java - 数组类在 Java 中如何工作?

java - 创建 jar 文件时 SwingWorker 不工作

java - Java 中的 Neo4j Cypher 查询结果序列化

java - 执行时间计算的准确度如何?