Possible Duplicate:
What makes JNI calls slow?
First let me say that this questions is born more out of curiosity than real necessity.
I’m curious to know what is the overhead in doing a JNI call from Java, with say, System.arraycopy versus allocating the array and copying the elements over with a for loop.
If the overhead is substantial, then there is probably a rough “magic number” of elements up to which it compensates to simply use a for loop, instead of using the System call. And also, what exactly is involved in the System call that causes this overhead?
I’m guessing the stack must be pushed to the context of the call, and that might take a while, but I can’t find a good explanation for the whole process.
Let me clarify my question:
I know that using arraycopy is the fastest way to copy an array in Java.
That being said, let’s say I’m using it to copy an array of only one element. Since I’m calling the underlying OS to do so, there has to be an overhead in this call. I’m interested in knowing what this overhead is and what happens in the process of the call.
I’m sorry if using arraycopy misled you from the purpose of my question. I’m interested to know the overhead of a JNI call, and what’s involved in the actual call.
You are right that system calls are fairly expensive. However, the
SysteminSystem.arraycopy()is a bit of a misnomer. There are no system calls involved.When you look at the definition of
System.arraycopy(), it’s declared asnative. This means that the method is implemented in C++. If you were so inclined, you could look at the JDK source code, and find the C++ function. In OpenJDK 7, it’s calledJVM_ArrayCopy()and lives inhotspot/src/share/vm/prims/jvm.cpp. The implementation is surprisingly complicated, but deep down it’s essentially amemcpy().If
arraycopy()is being used as a normal native function, there’s overhead to calling it. There’s further overhead caused by argument checking etc.However, it’s very likely that the JIT compiler knows about
System.arraycopy(). This means that, instead of calling the C++ function, the compiler knows how to generate specially-crafted machine code to carry out the array copy. I don’t know about other JVMs, but HotSpot does have such “intrinsic” support forSystem.arraycopy().If your array is tiny, you may be able to beat
System.arraycopy()with a hand-crafted loop. You can probably do even better if the size is known at compile time, since then you can also unroll the loop. However, all of that is not really relevant except in the narrowest of circumstances.