├── settings.gradle ├── .gitignore ├── panama └── kernel32.h.jar ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── src ├── main │ └── java │ │ └── com │ │ └── zakgof │ │ └── jnbenchmark │ │ ├── jnr │ │ ├── Kernel32.java │ │ ├── JnrBenchmark.java │ │ └── SYSTEMTIME.java │ │ ├── bridj │ │ ├── Kernel32.java │ │ ├── BridjBenchmark.java │ │ └── SYSTEMTIME.java │ │ ├── java │ │ └── JustJava.java │ │ ├── jna │ │ ├── JnaBenchmark.java │ │ └── JnaDirectBenchmark.java │ │ ├── jni │ │ └── JavaCppStock.java │ │ └── foreign │ │ └── JdkForeignBenchmark.java └── jmh │ └── java │ └── com │ └── zakgof │ └── jnbenchmark │ ├── JmhCallOnly.java │ └── JmhGetSystemTimeSeconds.java ├── gradlew.bat ├── README.md └── gradlew /settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'java-native-benchmark' 2 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | bin 2 | build 3 | target 4 | .gradle 5 | .settings 6 | .project 7 | .classpath -------------------------------------------------------------------------------- /panama/kernel32.h.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zakgof/java-native-benchmark/HEAD/panama/kernel32.h.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zakgof/java-native-benchmark/HEAD/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-8.3-rc-3-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /src/main/java/com/zakgof/jnbenchmark/jnr/Kernel32.java: -------------------------------------------------------------------------------- 1 | package com.zakgof.jnbenchmark.jnr; 2 | 3 | import jnr.ffi.CallingConvention; 4 | import jnr.ffi.LibraryLoader; 5 | import jnr.ffi.Runtime; 6 | 7 | public interface Kernel32 { 8 | 9 | public static final Kernel32 INSTANCE = LibraryLoader.create(Kernel32.class) 10 | .convention(CallingConvention.STDCALL) 11 | .load("Kernel32"); 12 | 13 | public static final Runtime RUNTIME = Runtime.getRuntime(INSTANCE); 14 | 15 | int GetSystemTime(SYSTEMTIME pSystemTime); 16 | } -------------------------------------------------------------------------------- /src/main/java/com/zakgof/jnbenchmark/bridj/Kernel32.java: -------------------------------------------------------------------------------- 1 | package com.zakgof.jnbenchmark.bridj; 2 | 3 | import org.bridj.BridJ; 4 | import org.bridj.CRuntime; 5 | import org.bridj.Pointer; 6 | import org.bridj.ann.Library; 7 | import org.bridj.ann.Name; 8 | import org.bridj.ann.Runtime; 9 | 10 | @Library("kernel32") 11 | @Runtime(CRuntime.class) 12 | public class Kernel32 { 13 | static { 14 | BridJ.register(); 15 | } 16 | @Name("GetSystemTime") 17 | public native void getSystemTime(Pointer lpSystemTime); 18 | } 19 | -------------------------------------------------------------------------------- /src/main/java/com/zakgof/jnbenchmark/java/JustJava.java: -------------------------------------------------------------------------------- 1 | package com.zakgof.jnbenchmark.java; 2 | 3 | import java.time.LocalDateTime; 4 | import java.util.Calendar; 5 | import java.util.Date; 6 | 7 | public class JustJava { 8 | 9 | public static int java_calendar() { 10 | return Calendar.getInstance().get(Calendar.SECOND); 11 | } 12 | 13 | public static int java_ldt() { 14 | return LocalDateTime.now().getSecond(); 15 | } 16 | 17 | @SuppressWarnings("deprecation") 18 | public static int java_date() { 19 | return new Date().getSeconds(); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/main/java/com/zakgof/jnbenchmark/jnr/JnrBenchmark.java: -------------------------------------------------------------------------------- 1 | package com.zakgof.jnbenchmark.jnr; 2 | 3 | public class JnrBenchmark { 4 | 5 | private SYSTEMTIME preallocatedSystemTime; 6 | 7 | public JnrBenchmark() { 8 | preallocatedSystemTime = new SYSTEMTIME(Kernel32.RUNTIME); 9 | } 10 | 11 | public void callOnly() { 12 | Kernel32.INSTANCE.GetSystemTime(preallocatedSystemTime); 13 | } 14 | 15 | public static short all() { 16 | SYSTEMTIME systemtime = new SYSTEMTIME(Kernel32.RUNTIME); 17 | Kernel32.INSTANCE.GetSystemTime(systemtime); 18 | return systemtime.wSecond.shortValue(); 19 | } 20 | 21 | } 22 | -------------------------------------------------------------------------------- /src/main/java/com/zakgof/jnbenchmark/jnr/SYSTEMTIME.java: -------------------------------------------------------------------------------- 1 | package com.zakgof.jnbenchmark.jnr; 2 | 3 | import jnr.ffi.Runtime; 4 | import jnr.ffi.Struct; 5 | 6 | public class SYSTEMTIME extends Struct { 7 | protected SYSTEMTIME(Runtime runtime) { 8 | super(runtime); 9 | } 10 | 11 | public final WORD wYear = new WORD(); 12 | public final WORD wMonth = new WORD(); 13 | public final WORD wDayOfWeek = new WORD(); 14 | public final WORD wDay = new WORD(); 15 | public final WORD wHour = new WORD(); 16 | public final WORD wMinute = new WORD(); 17 | public final WORD wSecond = new WORD(); 18 | public final WORD wMilliseconds = new WORD(); 19 | } -------------------------------------------------------------------------------- /src/main/java/com/zakgof/jnbenchmark/jna/JnaBenchmark.java: -------------------------------------------------------------------------------- 1 | package com.zakgof.jnbenchmark.jna; 2 | 3 | import com.sun.jna.platform.win32.Kernel32; 4 | import com.sun.jna.platform.win32.WinBase; 5 | 6 | public class JnaBenchmark { 7 | 8 | private final WinBase.SYSTEMTIME preallocatedSystemtime; 9 | 10 | public JnaBenchmark() { 11 | preallocatedSystemtime = new WinBase.SYSTEMTIME(); 12 | } 13 | 14 | public void callOnly() { 15 | Kernel32.INSTANCE.GetSystemTime(preallocatedSystemtime); 16 | } 17 | 18 | public static short all() { 19 | WinBase.SYSTEMTIME systemtime = new WinBase.SYSTEMTIME(); 20 | Kernel32.INSTANCE.GetSystemTime(systemtime); 21 | return systemtime.wSecond; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/main/java/com/zakgof/jnbenchmark/bridj/BridjBenchmark.java: -------------------------------------------------------------------------------- 1 | package com.zakgof.jnbenchmark.bridj; 2 | 3 | import org.bridj.Pointer; 4 | 5 | public class BridjBenchmark { 6 | 7 | private Pointer preallocatedPointer; 8 | private static Kernel32 kernel32 = new Kernel32(); 9 | 10 | public BridjBenchmark() { 11 | SYSTEMTIME systemtime = new SYSTEMTIME(); 12 | preallocatedPointer = Pointer.getPointer(systemtime); 13 | } 14 | 15 | public void callOnly() { 16 | kernel32.getSystemTime(preallocatedPointer); 17 | } 18 | 19 | public static short all() { 20 | SYSTEMTIME systime = new SYSTEMTIME(); 21 | kernel32.getSystemTime(Pointer.getPointer(systime)); 22 | return systime.wSecond(); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/main/java/com/zakgof/jnbenchmark/jna/JnaDirectBenchmark.java: -------------------------------------------------------------------------------- 1 | package com.zakgof.jnbenchmark.jna; 2 | 3 | import com.sun.jna.Native; 4 | import com.sun.jna.platform.win32.WinBase; 5 | import com.sun.jna.platform.win32.WinBase.SYSTEMTIME; 6 | 7 | public class JnaDirectBenchmark { 8 | 9 | static { 10 | Native.register("kernel32"); 11 | } 12 | 13 | private WinBase.SYSTEMTIME preallocatedSystemtime; 14 | 15 | native static void GetSystemTime(SYSTEMTIME lpSystemTime); 16 | 17 | public JnaDirectBenchmark() { 18 | preallocatedSystemtime = new WinBase.SYSTEMTIME(); 19 | } 20 | 21 | public void callOnly() { 22 | GetSystemTime(preallocatedSystemtime); 23 | } 24 | 25 | public static short all() { 26 | WinBase.SYSTEMTIME systemtime = new WinBase.SYSTEMTIME(); 27 | GetSystemTime(systemtime); 28 | return systemtime.wSecond; 29 | } 30 | 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/com/zakgof/jnbenchmark/jni/JavaCppStock.java: -------------------------------------------------------------------------------- 1 | package com.zakgof.jnbenchmark.jni; 2 | 3 | import org.bytedeco.javacpp.Pointer; 4 | import org.bytedeco.javacpp.windows; 5 | import org.bytedeco.javacpp.windows.SYSTEMTIME; 6 | 7 | public class JavaCppStock { 8 | 9 | private static final long SYSTEMTIME_STRUCT_LENGTH = 16; // precalculated as new SYSTEMTIME().sizeof(); 10 | private SYSTEMTIME preallocatedSystemTime; 11 | 12 | public JavaCppStock() { 13 | preallocatedSystemTime = new SYSTEMTIME(); 14 | } 15 | 16 | public void callOnly() { 17 | windows.GetSystemTime(preallocatedSystemTime); 18 | } 19 | 20 | public static short all() { 21 | SYSTEMTIME systemtime = new SYSTEMTIME(Pointer.malloc(SYSTEMTIME_STRUCT_LENGTH)); // new SYSTEMTIME() is much slower, see https://github.com/bytedeco/javacpp/issues/299 22 | windows.GetSystemTime(systemtime); 23 | return systemtime.wSecond(); 24 | } 25 | 26 | } 27 | -------------------------------------------------------------------------------- /src/main/java/com/zakgof/jnbenchmark/bridj/SYSTEMTIME.java: -------------------------------------------------------------------------------- 1 | package com.zakgof.jnbenchmark.bridj; 2 | 3 | import org.bridj.BridJ; 4 | import org.bridj.Pointer; 5 | import org.bridj.StructObject; 6 | import org.bridj.ann.Field; 7 | import org.bridj.ann.Library; 8 | 9 | @Library("kernel32") 10 | public class SYSTEMTIME extends StructObject { 11 | static { 12 | BridJ.register(); 13 | } 14 | @Field(0) 15 | public short wYear() { 16 | return this.io.getShortField(this, 0); 17 | } 18 | @Field(0) 19 | public SYSTEMTIME wYear(short wYear) { 20 | this.io.setShortField(this, 0, wYear); 21 | return this; 22 | } 23 | @Field(1) 24 | public short wMonth() { 25 | return this.io.getShortField(this, 1); 26 | } 27 | @Field(1) 28 | public SYSTEMTIME wMonth(short wMonth) { 29 | this.io.setShortField(this, 1, wMonth); 30 | return this; 31 | } 32 | @Field(2) 33 | public short wDayOfWeek() { 34 | return this.io.getShortField(this, 2); 35 | } 36 | @Field(2) 37 | public SYSTEMTIME wDayOfWeek(short wDayOfWeek) { 38 | this.io.setShortField(this, 2, wDayOfWeek); 39 | return this; 40 | } 41 | @Field(3) 42 | public short wDay() { 43 | return this.io.getShortField(this, 3); 44 | } 45 | @Field(3) 46 | public SYSTEMTIME wDay(short wDay) { 47 | this.io.setShortField(this, 3, wDay); 48 | return this; 49 | } 50 | @Field(4) 51 | public short wHour() { 52 | return this.io.getShortField(this, 4); 53 | } 54 | @Field(4) 55 | public SYSTEMTIME wHour(short wHour) { 56 | this.io.setShortField(this, 4, wHour); 57 | return this; 58 | } 59 | @Field(5) 60 | public short wMinute() { 61 | return this.io.getShortField(this, 5); 62 | } 63 | @Field(5) 64 | public SYSTEMTIME wMinute(short wMinute) { 65 | this.io.setShortField(this, 5, wMinute); 66 | return this; 67 | } 68 | @Field(6) 69 | public short wSecond() { 70 | return this.io.getShortField(this, 6); 71 | } 72 | @Field(6) 73 | public SYSTEMTIME wSecond(short wSecond) { 74 | this.io.setShortField(this, 6, wSecond); 75 | return this; 76 | } 77 | @Field(7) 78 | public short wMilliseconds() { 79 | return this.io.getShortField(this, 7); 80 | } 81 | @Field(7) 82 | public SYSTEMTIME wMilliseconds(short wMilliseconds) { 83 | this.io.setShortField(this, 7, wMilliseconds); 84 | return this; 85 | } 86 | public SYSTEMTIME() { 87 | super(); 88 | } 89 | public SYSTEMTIME(Pointer pointer) { 90 | super(pointer); 91 | } 92 | } 93 | -------------------------------------------------------------------------------- /src/jmh/java/com/zakgof/jnbenchmark/JmhCallOnly.java: -------------------------------------------------------------------------------- 1 | package com.zakgof.jnbenchmark; 2 | 3 | import com.zakgof.jnbenchmark.bridj.BridjBenchmark; 4 | import com.zakgof.jnbenchmark.foreign.JdkForeignBenchmark; 5 | import com.zakgof.jnbenchmark.jna.JnaBenchmark; 6 | import com.zakgof.jnbenchmark.jna.JnaDirectBenchmark; 7 | import com.zakgof.jnbenchmark.jni.JavaCppStock; 8 | import com.zakgof.jnbenchmark.jnr.JnrBenchmark; 9 | import org.openjdk.jmh.annotations.Benchmark; 10 | import org.openjdk.jmh.annotations.BenchmarkMode; 11 | import org.openjdk.jmh.annotations.Level; 12 | import org.openjdk.jmh.annotations.Measurement; 13 | import org.openjdk.jmh.annotations.Mode; 14 | import org.openjdk.jmh.annotations.OutputTimeUnit; 15 | import org.openjdk.jmh.annotations.Scope; 16 | import org.openjdk.jmh.annotations.Setup; 17 | import org.openjdk.jmh.annotations.State; 18 | import org.openjdk.jmh.annotations.Warmup; 19 | 20 | import java.util.concurrent.TimeUnit; 21 | 22 | @BenchmarkMode(Mode.AverageTime) 23 | @Warmup(iterations = 5, time = 500, timeUnit = TimeUnit.MILLISECONDS) 24 | @Measurement(iterations = 10, time = 500, timeUnit = TimeUnit.MILLISECONDS) 25 | @State(Scope.Thread) 26 | @OutputTimeUnit(TimeUnit.NANOSECONDS) 27 | public class JmhCallOnly { 28 | 29 | private JdkForeignBenchmark foreign; 30 | private JavaCppStock javacppjni; 31 | private BridjBenchmark bridj; 32 | private JnaBenchmark jna; 33 | private JnaDirectBenchmark jnaDirect; 34 | private JnrBenchmark jnr; 35 | 36 | @Setup(Level.Trial) 37 | public void setup() { 38 | foreign = new JdkForeignBenchmark(); 39 | javacppjni = new JavaCppStock(); 40 | bridj = new BridjBenchmark(); 41 | jna = new JnaBenchmark(); 42 | jnaDirect = new JnaDirectBenchmark(); 43 | jnr = new JnrBenchmark(); 44 | } 45 | 46 | @Benchmark 47 | public void jni_javacpp() throws InterruptedException { 48 | javacppjni.callOnly(); 49 | } 50 | 51 | @Benchmark 52 | public void foreign() throws InterruptedException { 53 | foreign.callOnly(); 54 | } 55 | 56 | @Benchmark 57 | public void bridj() throws InterruptedException { 58 | bridj.callOnly(); 59 | } 60 | 61 | @Benchmark 62 | public void jna() throws InterruptedException { 63 | jna.callOnly(); 64 | } 65 | 66 | @Benchmark 67 | public void jna_direct() throws InterruptedException { 68 | jnaDirect.callOnly(); 69 | } 70 | 71 | @Benchmark 72 | public void jnr() throws InterruptedException { 73 | jnr.callOnly(); 74 | } 75 | 76 | } 77 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | set DIRNAME=%~dp0 12 | if "%DIRNAME%" == "" set DIRNAME=. 13 | set APP_BASE_NAME=%~n0 14 | set APP_HOME=%DIRNAME% 15 | 16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 17 | set DEFAULT_JVM_OPTS= 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windows variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | 53 | :win9xME_args 54 | @rem Slurp the command line arguments. 55 | set CMD_LINE_ARGS= 56 | set _SKIP=2 57 | 58 | :win9xME_args_slurp 59 | if "x%~1" == "x" goto execute 60 | 61 | set CMD_LINE_ARGS=%* 62 | 63 | :execute 64 | @rem Setup the command line 65 | 66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 67 | 68 | @rem Execute Gradle 69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 70 | 71 | :end 72 | @rem End local scope for the variables with windows NT shell 73 | if "%ERRORLEVEL%"=="0" goto mainEnd 74 | 75 | :fail 76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 77 | rem the _cmd.exe /c_ return code! 78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 79 | exit /b 1 80 | 81 | :mainEnd 82 | if "%OS%"=="Windows_NT" endlocal 83 | 84 | :omega 85 | -------------------------------------------------------------------------------- /src/jmh/java/com/zakgof/jnbenchmark/JmhGetSystemTimeSeconds.java: -------------------------------------------------------------------------------- 1 | package com.zakgof.jnbenchmark; 2 | 3 | import com.zakgof.jnbenchmark.bridj.BridjBenchmark; 4 | import com.zakgof.jnbenchmark.foreign.JdkForeignBenchmark; 5 | import com.zakgof.jnbenchmark.java.JustJava; 6 | import com.zakgof.jnbenchmark.jna.JnaBenchmark; 7 | import com.zakgof.jnbenchmark.jna.JnaDirectBenchmark; 8 | import com.zakgof.jnbenchmark.jni.JavaCppStock; 9 | import com.zakgof.jnbenchmark.jnr.JnrBenchmark; 10 | import org.openjdk.jmh.annotations.Benchmark; 11 | import org.openjdk.jmh.annotations.BenchmarkMode; 12 | import org.openjdk.jmh.annotations.Level; 13 | import org.openjdk.jmh.annotations.Measurement; 14 | import org.openjdk.jmh.annotations.Mode; 15 | import org.openjdk.jmh.annotations.OutputTimeUnit; 16 | import org.openjdk.jmh.annotations.Scope; 17 | import org.openjdk.jmh.annotations.Setup; 18 | import org.openjdk.jmh.annotations.State; 19 | import org.openjdk.jmh.annotations.Warmup; 20 | 21 | import java.util.concurrent.TimeUnit; 22 | 23 | @BenchmarkMode(Mode.AverageTime) 24 | @Warmup(iterations = 5, time = 500, timeUnit = TimeUnit.MILLISECONDS) 25 | @Measurement(iterations = 10, time = 500, timeUnit = TimeUnit.MILLISECONDS) 26 | @State(Scope.Thread) 27 | @OutputTimeUnit(TimeUnit.NANOSECONDS) 28 | public class JmhGetSystemTimeSeconds { 29 | 30 | private JdkForeignBenchmark foreign; 31 | 32 | @Setup(Level.Trial) 33 | public void setup() { 34 | foreign = new JdkForeignBenchmark(); 35 | } 36 | 37 | @Benchmark 38 | public void java_localdatetime() throws InterruptedException { 39 | JustJava.java_ldt(); 40 | } 41 | 42 | @Benchmark 43 | public void java_calendar() throws InterruptedException { 44 | JustJava.java_calendar(); 45 | } 46 | 47 | @Benchmark 48 | public void java_date() throws InterruptedException { 49 | JustJava.java_date(); 50 | } 51 | 52 | @Benchmark 53 | public void jni_javacpp() throws InterruptedException { 54 | JavaCppStock.all(); 55 | } 56 | 57 | @Benchmark 58 | public void jna() throws InterruptedException { 59 | JnaBenchmark.all(); 60 | } 61 | 62 | @Benchmark 63 | public void jnaDirect() throws InterruptedException { 64 | JnaDirectBenchmark.all(); 65 | } 66 | 67 | @Benchmark 68 | public void jnr() throws InterruptedException { 69 | JnrBenchmark.all(); 70 | } 71 | 72 | @Benchmark 73 | public void bridj() throws InterruptedException { 74 | BridjBenchmark.all(); 75 | } 76 | 77 | @Benchmark 78 | public void foreign() throws InterruptedException { 79 | foreign.all(); 80 | } 81 | 82 | } 83 | -------------------------------------------------------------------------------- /src/main/java/com/zakgof/jnbenchmark/foreign/JdkForeignBenchmark.java: -------------------------------------------------------------------------------- 1 | package com.zakgof.jnbenchmark.foreign; 2 | 3 | import java.lang.foreign.FunctionDescriptor; 4 | import java.lang.foreign.Linker; 5 | import java.lang.foreign.MemoryLayout; 6 | import java.lang.foreign.MemorySegment; 7 | import java.lang.foreign.MemorySession; 8 | import java.lang.foreign.SymbolLookup; 9 | import java.lang.invoke.MethodHandle; 10 | import java.lang.invoke.VarHandle; 11 | 12 | import static java.lang.foreign.MemoryLayout.structLayout; 13 | import static java.lang.foreign.ValueLayout.ADDRESS; 14 | import static java.lang.foreign.ValueLayout.JAVA_SHORT; 15 | 16 | public class JdkForeignBenchmark { 17 | 18 | private static final MemoryLayout SYSTEMTIME = structLayout( 19 | JAVA_SHORT.withName("wYear"), 20 | JAVA_SHORT.withName("wMonth"), 21 | JAVA_SHORT.withName("wDayOfWeek"), 22 | JAVA_SHORT.withName("wDay"), 23 | JAVA_SHORT.withName("wHour"), 24 | JAVA_SHORT.withName("wMinute"), 25 | JAVA_SHORT.withName("wSecond"), 26 | JAVA_SHORT.withName("wMilliseconds") 27 | ); 28 | 29 | private final VarHandle wSecondHandle; 30 | private final MethodHandle mhGetSystemTime; 31 | private final MemorySegment globalSystemTime; 32 | private final MemorySession globalMemorySession; 33 | 34 | 35 | public JdkForeignBenchmark() { 36 | 37 | System.loadLibrary("Kernel32"); 38 | SymbolLookup lookup = SymbolLookup.loaderLookup(); 39 | Linker linker = Linker.nativeLinker(); 40 | MemorySegment getSystemTime = lookup.lookup("GetSystemTime").orElseThrow(); 41 | 42 | this.wSecondHandle = SYSTEMTIME.varHandle(MemoryLayout.PathElement.groupElement("wSecond")); 43 | 44 | 45 | this.mhGetSystemTime = linker.downcallHandle(getSystemTime, FunctionDescriptor.ofVoid(ADDRESS)); 46 | 47 | globalMemorySession = MemorySession.global(); 48 | globalSystemTime = globalMemorySession.allocate(SYSTEMTIME); 49 | } 50 | 51 | public short all() { 52 | try { 53 | MemorySegment lpSystemTime = globalMemorySession.allocate(SYSTEMTIME); 54 | mhGetSystemTime.invoke(lpSystemTime); 55 | return (Short) wSecondHandle.get(lpSystemTime); 56 | } catch (Throwable e) { 57 | throw new RuntimeException(e); 58 | } 59 | } 60 | 61 | public void callOnly() { 62 | try { 63 | mhGetSystemTime.invoke(globalSystemTime); 64 | } catch (Throwable e) { 65 | throw new RuntimeException(e); 66 | } 67 | } 68 | 69 | } 70 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # java-native-benchmark 2 | JMH performance benchmark for Java's native call APIs: [JNI](https://docs.oracle.com/en/java/javase/12/docs/specs/jni/index.html) (via [JavaCpp](https://github.com/bytedeco/javacpp) ), [JNA](https://github.com/java-native-access/jna), [JNR](https://github.com/jnr/jnr-ffi), [Bridj](https://github.com/nativelibs4java/BridJ) and [JDK JEP-424](https://openjdk.org/jeps/424) Foreign Function/Memory APIs (Preview). 3 | 4 | Updated **August 9, 2023** 5 | 6 | See historical results here: [August 2019](https://github.com/zakgof/java-native-benchmark/tree/August-2019#readme) 7 | 8 | ## Benchmark operation ## 9 | Get seconds from the current system time using native call to Windows API function `GetSystemTime` provided by kernel32.dll: 10 | 11 | ````cpp 12 | void GetSystemTime(LPSYSTEMTIME lpSystemTime); 13 | ```` 14 | with the data structure defined as 15 | ````cpp 16 | typedef struct _SYSTEMTIME { 17 | WORD wYear; 18 | WORD wMonth; 19 | WORD wDayOfWeek; 20 | WORD wDay; 21 | WORD wHour; 22 | WORD wMinute; 23 | WORD wSecond; 24 | WORD wMilliseconds; 25 | } SYSTEMTIME, *PSYSTEMTIME, *LPSYSTEMTIME; 26 | ```` 27 | Each implementation will 28 | 1. allocate memory for the `SYSTEMTIME` struct 29 | 2. call native method `GetSystemTime` passing the allocated memory 30 | 3. extract and return the value from the field `wSecond` 31 | 32 | In a separate benchmark I measured performance of the native call only (item 2). 33 | 34 | **JNI** 35 | JNI is a Java's standard way to call native code present in JDK since its early versions. JNI requires building a native stub as an adapter between Java and native library, so is considered low-level. Helper tools have been developed in order to automate and simplify native stub generation. Here I used [JavaCpp](https://github.com/bytedeco/javacpp), the project is known for prebaking Java wrappers around high-performant C/C++ libraries such as OpenCV and ffmpeg. 36 | JavaCpp comes with ready-to-use wrappers for widely used system libraries, including Windows API lib, so I used them in this benchmark. 37 | 38 | **JNA** 39 | JNA resolves the burden of writing native wrapper by using a native stub that calls the target function dynamically. It only requires writing Java code and provides mapping to C structs and unions, however, for complex libraries writing Java API that matched a native lib's C API still might be a big task. JNA also provides prebaked Java classes for Windows API. Wrapping the calls dynamically results in high performance overhead comparing to JNI. 40 | 41 | **JNA Direct** 42 | JNA's direct mode claims to "improve performance substantially, approaching that of custom JNI". That should be well seen then calls are using mostly primitive types for arguments and return values. 43 | 44 | **BriJ** 45 | Bridj is an attempt to provide a Java to Cpp interop solution similar to JNA (without a need of writing and compiling native code), it claims to provide better performance using dyncall and hand-optimized assembly tweaks. A tool named JNAerator helps to generate java classed from the native library headers. The Bridj projects seems to be abandoned now. 46 | 47 | **JNR** 48 | JNR is a comparingly young project that target the same problem. Similarly as JNA or Bridj it does not require native programming. There's not much documentation or reviews at the moment, but JNR is often called promising. 49 | 50 | **JDK Foreign Function/Memory API Preview (JEP-424)** 51 | API by which Java programs can interoperate with code and data outside of the Java runtime. 52 | 53 | **Pure Java** 54 | For comparison, the same problem was implemented with JDK's `java.util.Date`, `java.util.Calendar` and `java.time.LocalDateTime` 55 | 56 | ## How to run ## 57 | 58 | Make sure that gradle is configured with a JDK 19 and run 59 | ```` 60 | gradlew clean jmh 61 | ```` 62 | 63 | ## Results ## 64 | 65 | **System**: 66 | 67 | Intel Core i7-10610U CPU @ 1.80GHz / Windows 10 / openjdk-19.0.1 68 | ``` 69 | Full benchmark (average time, smaller is better) 70 | 71 | JmhGetSystemTimeSeconds.jnaDirect 4517.766 ± 417.656 ns/op 72 | JmhGetSystemTimeSeconds.jna 4037.103 ± 681.270 ns/op 73 | JmhGetSystemTimeSeconds.bridj 1087.531 ± 122.028 ns/op 74 | JmhGetSystemTimeSeconds.jnr 400.896 ± 52.783 ns/op 75 | JmhGetSystemTimeSeconds.jni_javacpp 259.521 ± 7.964 ns/op 76 | JmhGetSystemTimeSeconds.foreign 237.920 ± 30.081 ns/op 77 | JmhGetSystemTimeSeconds.java_calendar 154.341 ± 8.306 ns/op 78 | JmhGetSystemTimeSeconds.java_localdatetime 85.310 ± 32.671 ns/op 79 | JmhGetSystemTimeSeconds.java_date 58.209 ± 3.257 ns/op 80 | 81 | ``` 82 | 83 | JNA looks expectedly slow (x13 slower that JNI). JNA direct appears even slower, as probably mapping the struct from C to Java consumes the most of operation's time. 84 | 85 | JNR appears faster than outdated Bridj, yet staying behind JNI. 86 | 87 | JDK's foreign APIs demonstrate performance twice faster than JNI. This looks much better than 2019 results confirming that the significant performance optimization tool place within JDKs 15-19. 88 | 89 | Foreign APIs itself are still a little slower than pure Java. Note that the fastest API was `java.util.Date` (with a deprecated but still working `Date.getSeconds`). The JDK8+'s `LocalDateTime` is ~2.4 times faster than Calendar API, but yet a little slower than the old-style `j.u.Date`. 90 | 91 | 92 | Now let's look into performance of the native call only, stripping out the struct allocation and field access: 93 | 94 | ```` 95 | Native call only (average time, smaller is better) 96 | 97 | JmhCallOnly.jna_direct 1373.435 ± 70.343 ns/op 98 | JmhCallOnly.jna 1346.036 ± 72.239 ns/op 99 | JmhCallOnly.bridj 383.992 ± 50.000 ns/op 100 | JmhCallOnly.jnr 298.334 ± 48.785 ns/op 101 | JmhCallOnly.jni_javacpp 56.605 ± 8.087 ns/op 102 | JmhCallOnly.foreign 49.717 ± 6.667 ns/op 103 | ```` 104 | The order is nearly the same, and Panama is a leader. 105 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Attempt to set APP_HOME 10 | # Resolve links: $0 may be a link 11 | PRG="$0" 12 | # Need this for relative symlinks. 13 | while [ -h "$PRG" ] ; do 14 | ls=`ls -ld "$PRG"` 15 | link=`expr "$ls" : '.*-> \(.*\)$'` 16 | if expr "$link" : '/.*' > /dev/null; then 17 | PRG="$link" 18 | else 19 | PRG=`dirname "$PRG"`"/$link" 20 | fi 21 | done 22 | SAVED="`pwd`" 23 | cd "`dirname \"$PRG\"`/" >/dev/null 24 | APP_HOME="`pwd -P`" 25 | cd "$SAVED" >/dev/null 26 | 27 | APP_NAME="Gradle" 28 | APP_BASE_NAME=`basename "$0"` 29 | 30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 31 | DEFAULT_JVM_OPTS="" 32 | 33 | # Use the maximum available, or set MAX_FD != -1 to use that value. 34 | MAX_FD="maximum" 35 | 36 | warn () { 37 | echo "$*" 38 | } 39 | 40 | die () { 41 | echo 42 | echo "$*" 43 | echo 44 | exit 1 45 | } 46 | 47 | # OS specific support (must be 'true' or 'false'). 48 | cygwin=false 49 | msys=false 50 | darwin=false 51 | nonstop=false 52 | case "`uname`" in 53 | CYGWIN* ) 54 | cygwin=true 55 | ;; 56 | Darwin* ) 57 | darwin=true 58 | ;; 59 | MINGW* ) 60 | msys=true 61 | ;; 62 | NONSTOP* ) 63 | nonstop=true 64 | ;; 65 | esac 66 | 67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 68 | 69 | # Determine the Java command to use to start the JVM. 70 | if [ -n "$JAVA_HOME" ] ; then 71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 72 | # IBM's JDK on AIX uses strange locations for the executables 73 | JAVACMD="$JAVA_HOME/jre/sh/java" 74 | else 75 | JAVACMD="$JAVA_HOME/bin/java" 76 | fi 77 | if [ ! -x "$JAVACMD" ] ; then 78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 79 | 80 | Please set the JAVA_HOME variable in your environment to match the 81 | location of your Java installation." 82 | fi 83 | else 84 | JAVACMD="java" 85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 86 | 87 | Please set the JAVA_HOME variable in your environment to match the 88 | location of your Java installation." 89 | fi 90 | 91 | # Increase the maximum file descriptors if we can. 92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 93 | MAX_FD_LIMIT=`ulimit -H -n` 94 | if [ $? -eq 0 ] ; then 95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 96 | MAX_FD="$MAX_FD_LIMIT" 97 | fi 98 | ulimit -n $MAX_FD 99 | if [ $? -ne 0 ] ; then 100 | warn "Could not set maximum file descriptor limit: $MAX_FD" 101 | fi 102 | else 103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 104 | fi 105 | fi 106 | 107 | # For Darwin, add options to specify how the application appears in the dock 108 | if $darwin; then 109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 110 | fi 111 | 112 | # For Cygwin, switch paths to Windows format before running java 113 | if $cygwin ; then 114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 116 | JAVACMD=`cygpath --unix "$JAVACMD"` 117 | 118 | # We build the pattern for arguments to be converted via cygpath 119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 120 | SEP="" 121 | for dir in $ROOTDIRSRAW ; do 122 | ROOTDIRS="$ROOTDIRS$SEP$dir" 123 | SEP="|" 124 | done 125 | OURCYGPATTERN="(^($ROOTDIRS))" 126 | # Add a user-defined pattern to the cygpath arguments 127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 129 | fi 130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 131 | i=0 132 | for arg in "$@" ; do 133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 135 | 136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 138 | else 139 | eval `echo args$i`="\"$arg\"" 140 | fi 141 | i=$((i+1)) 142 | done 143 | case $i in 144 | (0) set -- ;; 145 | (1) set -- "$args0" ;; 146 | (2) set -- "$args0" "$args1" ;; 147 | (3) set -- "$args0" "$args1" "$args2" ;; 148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 154 | esac 155 | fi 156 | 157 | # Escape application args 158 | save () { 159 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 160 | echo " " 161 | } 162 | APP_ARGS=$(save "$@") 163 | 164 | # Collect all arguments for the java command, following the shell quoting and substitution rules 165 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 166 | 167 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong 168 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then 169 | cd "$(dirname "$0")" 170 | fi 171 | 172 | exec "$JAVACMD" "$@" 173 | --------------------------------------------------------------------------------