问题描述
我知道在Java中进行JNI调用时跨越边界很慢。
I know that 'crossing boundaries' when making a JNI call in Java is slow.
但是我想知道是什么这会让它变慢吗?
在进行JNI调用时,底层的jvm实现做了什么让它变得如此之慢?
However I want to know what is it that makes it slow?What does the underlying jvm implementation do when making a JNI call that makes it so slow?
推荐答案
首先,它是值得注意的是,通过慢,我们谈论的事情可能需要几十纳秒。对于简单的原生方法,在2010年,我在Windows桌面上平均测量了40秒的呼叫,在我的Mac桌面上测量了11 ns。除非您正在进行许多调用,否则您将不会注意到。
First, it's worth noting that by "slow," we're talking about something that can take tens of nanoseconds. For trivial native methods, in 2010 I measured calls at an average 40 ns on my Windows desktop, and 11 ns on my Mac desktop. Unless you're making many calls, you're not going to notice.
也就是说,调用本机方法可以慢于比进行普通的Java方法调用。原因包括:
That said, calling a native method can be slower than making a normal Java method call. Causes include:
- JVM不会内联本机方法。它们也不会为这个特定的机器进行即时编译 - 它们已经编译好了。
- 可以复制Java数组以便在本机代码中进行访问,然后将其复制回来。成本可以是阵列大小的线性。我测量了100,000个阵列的JNI 复制,在我的Windows桌面上平均约为75微秒,在Mac上平均为82微秒。幸运的是,可以通过或,由@Philip在下面的评论中提供。
Some additional discussion, possibly dated, can be found in "Java¿ Platform Performance: Strategies and Tactics", 2000, by Steve Wilson and Jeff Kesselman, in section "9.2: Examining JNI costs". It's about a third of the way down this page, provided in the comment by @Philip below.
2009年IBM developerWorks论文提供了一些避免使用JNI的性能缺陷的建议。
The 2009 IBM developerWorks paper "Best practices for using the Java Native Interface" provides some suggestions on avoiding performance pitfalls with JNI.
这篇关于是什么让JNI呼叫变慢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!