views:

71

answers:

1

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?

+4  A: 

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.

Mark E