dev-resources.site
for different kinds of informations.
FFM (Foreign Function and Memory) Stdlib Example
Published at
11/7/2024
Categories
java
jni
Author
özkan pakdil
FFM is the new API trying to replace JNI and jep is here It is basically calling calling functions outside of JVM or accessing memory not managed by JVM. I wanted to test can FFM beat regular Java API, below you can find a simple test doing math sin with FFM and with regular Math.sin
import java.lang.foreign.FunctionDescriptor;
import java.lang.foreign.Linker;
import java.lang.foreign.MemorySegment;
import java.lang.foreign.SymbolLookup;
import java.lang.foreign.ValueLayout;
public class FFMSinTest {
public static void main(String[] args) throws Throwable {
Linker linker = Linker.nativeLinker();
SymbolLookup stdlib = linker.defaultLookup();
// Locate the "sin" function in the C math library
MemorySegment sinAddress = stdlib.find("sin").orElseThrow();
FunctionDescriptor descriptor = FunctionDescriptor.of(ValueLayout.JAVA_DOUBLE, ValueLayout.JAVA_DOUBLE);
var sinHandle = linker.downcallHandle(sinAddress, descriptor);
double angle = Math.PI / 4; // 45 degrees in radians
// Timing Java's Math.sin()
long javaStartTime = System.nanoTime();
for (int i = 0; i < 1_000_000; i++) {
double result = Math.sin(angle);
}
long javaEndTime = System.nanoTime();
long javaDuration = javaEndTime - javaStartTime;
// Timing C sin via FFM
long ffmStartTime = System.nanoTime();
for (int i = 0; i < 1_000_000; i++) {
double result = (double) sinHandle.invoke(angle);
}
long ffmEndTime = System.nanoTime();
long ffmDuration = ffmEndTime - ffmStartTime;
System.out.println("Java Math.sin() took: " + javaDuration / 1_000_000.0 + " ms");
System.out.println("C sin (FFM) took: " + ffmDuration / 1_000_000.0 + " ms");
}
}
And result is
Java Math.sin() took: 4.8677 ms
C sin (FFM) took: 78.9172 ms
In my laptop, lesson is “calling outside JVM is not a cheap process” 🤓
Articles
12 articles in total
What is load balancing and how to do it on client side
read article
How to find java app hosting(ISP) or How to deploy Spring Boot website to Koyeb
read article
How to deploy old php website to koyeb
read article
JetBrains developer stats of 2024
read article
How to generate a Aurora Postgresql cluster with all auto explain enabled
read article
How to containerize a rust warp app
read article
HashMap collisions and how JDK handles it
read article
Jetbrains Rider Endpoints
read article
Generating Flyway migrations using IntelliJ IDEA
read article
Native Image Quick Reference — GraalVM for JDK 23 - graalvm
read article
FFM (Foreign Function and Memory) Stdlib Example
currently reading
How to disable win11 startmenu internet search
read article
Featured ones: