Skip to content
Advertisement

What is the difference between Java intrinsic and native methods?

Java intrinsic functions are mentioned in various places (e.g. here). My understanding is that these are methods that handled with special native code. This seems similar to a JNI method which is also a block of native code.

What is the difference?

Advertisement

Answer

The JIT knows about intrinsics, so it can inline the relevant machine instruction into the code it’s JITing, and optimize around it as part of a hot loop.

A JNI function is a 100% black box for the compiler, with significant call/return overhead (especially if you use it for just a scalar).

But even if it were just a call to a function like int bitcount(unsigned x){ return __builtin_popcount(x); } that compiled to x86-64 popcnt eax, edi ; ret (x86-64 System V calling convention) the caller (which the JIT compiler is emitting) would still have to assume that all the call-clobbered registers were clobbered. On x86-64, that’s most of the integer registers and all the FP/vector registers. (Just like the cost for an ahead-of-time C++ compiler for calling a black-box function vs. an intrinsic). But I suspect the cost for calling a JNI function includes some extra overhead on top of that.

And of course a call to any unknown function means that variables which were in registers might need to be synced to memory if the JIT compiler can’t prove that nothing else has a reference to them. (Escape analysis.)

Plus, intrinsics mean the JVM understands what the function does, and can optimize through it. e.g. with constant propagation, it knows that popcount(5) = 2 set bits. But with an actual JNI function, it would still have to call it. And every call is a visible side-effect unless there’s some way to declare the function as “pure” so it can CSE.

With heavy inlining, compile time constants are not rare.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement