Video in progress

Strong Middle ⚙️ JVM and memory

What are JIT intrinsics, and why do System.arraycopy or the Math methods run faster than similar Java code?

An intrinsic is a method the JVM recognizes by name. The JIT doesn't compile its Java body but substitutes hand-written machine code tuned to the processor. SIMD and special CPU instructions (popcnt, crc32, AES) are used this way.

📖 Answer

In the JDK source, such methods are marked with the @IntrinsicCandidate annotation (up to JDK 16 it was @HotSpotIntrinsicCandidate). For example:

  • System.arraycopy, Arrays.equals, Arrays.fill, with vector instructions;
  • Integer.bitCount → a single popcnt;
  • Math.fma, Math.sqrt, Math.min/max;
  • String.indexOf, String.equals, the StringLatin1/StringUTF16 methods;
  • CRC32.update, CRC32C, AES/GCM, SHA, with hardware instructions;
  • Unsafe methods, Thread.onSpinWait() → pause.

That is why this kind of "optimization" usually loses:

// copying by hand: the JIT may vectorize it too, but there is no guarantee
for (int i = 0; i < n; i++) dst[i] = src[i];

// intrinsic: always the fastest path
System.arraycopy(src, 0, dst, 0, n);

Some intrinsics work in the interpreter too, but the main benefit is in C1/C2.

To see which ones were used:

java -XX:+UnlockDiagnosticVMOptions -XX:+PrintIntrinsics -jar app.jar

The practical lesson: think before replacing a standard library method with "I'll write a faster one myself". For example, your own CRC calculation can be several times slower than java.util.zip.CRC32C. And the reverse: intrinsics depend on the platform. ARM and x86 differ, so run benchmarks on the prod architecture.