Java is faster than the optimized Rust program

Danyal Mh
Towards Dev
Published in
2 min readFeb 16, 2022

--

hi. at first, I was a Rust programmer and wrote some projects and one framework for it, after hearing about Dynamic compilation technology, JVM made it attractive for me, I wrote a program in rust with many optimization flags for the compiler to get the best performance, and wrote instance in java.

after warm-up time I saw an amazing performance from JVM, its a beast and can beat Rust in performance,

Rust result: 10,648 _ 6,678 _ 8,274
Java result: 8,661 _ 9,608 _ 6,302

Average of 12 times benchmark :
Rust: 9,948
Java: 8,693

Java Code :

public static void main(String[] args) {
for (int q = 0; q < 1001; q++) {
long tInit = System.nanoTime();

ArrayList<CClass> arr = new ArrayList<CClass>(100);
for (int i = 0; i < 100 ; i++) {
arr.add(new CClass("fname", "lname", i % 30));
}

for (int i = 0; i < 100 ; i++) {
CClass cls = arr.get(i);
cls.validation();
}

if (q > 997) {
System.out.println(System.nanoTime() - tInit);
}
}

}

Rust Code :

fn main() {

for _ in 0..3 {
let now = std::time::Instant::now();
// ===============================================

let mut v = Vec::with_capacity(100);
for i in 0..100 {
v.push(Class::new("fname", "fname", i % 30));
}

for i in 0..100 {
let cls = v.get(i).unwrap();
cls.validation();
}


// ===============================================
let now2 = std::time::Instant::now();
println!("==> {}", now2.duration_since(now).as_nanos());
}
}

i use some rust compiler flag for maximize performance:

[build]rustflags=[“-C”, “target-cpu=native”][profile.dev]lto = trueopt-level = 3

and the end , i love more and more JVM , java/Scala
great language, huge ecosystem, and amazing performance,
Alibaba, Linkedin, Twitter, Amazon using 80% of backend of all work on JVM,

this is not just for independent or productivity of JVM
its it for amazing performance and Amazing stability

--

--