解释 Java 本机通信性能

发布于 2024-08-21 20:45:46 字数 256 浏览 6 评论 0原文

现在,我正在使用 JNA 进行 Java 本机通信,并且对其简单性感到满意。但是我确实需要优化性能并正在考虑使用其他绑定。

我的问题是:Java 原生通信的哪一部分是“昂贵”的部分?它们之间是数据的传递吗?

让我换一种说法。现在,我的 JNA 接口调用的函数根本不向 Java 传递任何数据,而且这些函数甚至不经常调用。换句话说,Java 调用一个库调用,然后该库调用暂时做自己的事情并返回一个基本类型。在这种情况下,JNI/Swig/etc 会比 JNA 更快吗?

Right now I'm using JNA for Java-native communication and am pleased with its simplicity. However I do need to optimize performance and am considering using other bindings.

My question is this: what part of Java-native communication is the "expensive" part? Is it the passing of data between them?

Let me put it another way. Right now the functions my JNA interface is calling don't pass any data to Java at all, and the functions aren't even called that often. In other words, Java calls a library call and then the library call does its own thing for a while and returns a primitive type. Will JNI/Swig/etc be any faster than JNA in that kind of situation?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

白芷 2024-08-28 20:45:46

鉴于您的用例,JNI 不会比 JNA 更快。

Java 原生交互的昂贵之处在于传输大量内存。特别是,让 Java 内存可供本机代码使用可能会非常昂贵; IIRC 这部分是因为 Java 可以选择按照自己喜欢的方式对内存进行分段,但本机代码需要连续的内存块——内存的移动/复制需要一些时间。

如果您担心性能,您应该确保您的 JNA 代码使用“直接”样式访问,而不是原始接口样式访问。

此外,如果您确实需要在 Java 和本机代码之间传输大量内存,您应该考虑使用单个初始直接分配(如果可能),并避免定期重新分配该内存。这样,您只需在开始时支付一次分配成本,因此经过大量调用后,该成本可以忽略不计。

Given your use-case JNI won't be any faster than JNA.

What's expensive about the Java-native interaction is transferring large amounts of memory. In particular, it can be very expensive to make Java memory available to the native code; IIRC this is partly because Java can choose to segment the memory however it likes, but native code will expect contiguous chunks of memory -- the movement/copying of memory takes some time.

If you're concerned about performance you should make sure that your JNA code uses the "direct" style access rather than the original interface style access.

Additionally, if you do need to transfer large amounts of memory between Java and native code you should consider using a single initial direct allocation (if possible) and avoid reallocating that memory on a regular basis. This way you pay the allocation cost only once, and at the beginning, so over a large number of calls that cost becomes negligible.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文