tags:

views:

494

answers:

4

Which is the fastest way of calling a native library from Java?

The ones I know about are

  • NativeCall - what we're currently using
  • JNA - haven't used it, but looks reasonable
  • JNI - looks horrendous to write, but we'll do it if we get the speed
+6  A: 

Swig makes JNI easier too.

In terms of speed, I suspect there will be subtle variations - I strongly suggest you pick a call that you know you'll be making a lot, and benchmark all of the solutions offered.

Jon Skeet
Downvoters: please explain, or the downvote is pointless...
Jon Skeet
+4  A: 

JNI is the fastest. JNA is very slow compared to JNI (the call overhead is probably one order of magnitude), but it is a fantastic library because it makes native access so easy. JNA is great if you need to make an occasional call to some native API. If you care about performance, I wouldn't use it in any "tight loops."

I'm not sure where NativeCall fits in the spectrum.

erickson
+2  A: 

This blog entry claims that due to the introspection mechanisms used by JNA, it'll be significantly slower than JNI. I suspect that NativeCall will use similar mechanisms and thus perform in a similar fashion.

However you should probably benchmark based on the particular objects you're referencing and/or marshalling between Java and C.

I would second the recommendation of SWIG. That makes life particularly easy (easier) for the Java/C interfacing.

Brian Agnew
JNI doesn't marshall. I don't think that JNA does either. Native and Java code both work with the same data in memory.
erickson
You have to undergo some form of object transfer - even if that's only a pointer reference.
Brian Agnew
Right, I just didn't want people to be confused that some sort of serialization is taking place; it's just pointers. The primary overhead is in introspection.
erickson
+1  A: 

Quite a few parameters influence the performances of interfaces between programing languages: what device the JVM runs on, who developed it (in case it's not the usual Sun JVM), whether you will need to call back Java code from native code, the threading model of the JVM on your operating system and how asynchronous will the native code be...

You may not find a reliable benchmark that measures exactly what you need, I'm afraid.

QuickRecipesOnSymbianOS