How to write a micro-benchmark in Java correctly? Pitfalls of JIT and optimizations
Hi everyone. I'm a beginner Java developer, and I need to measure the performance of two algorithm implementations: one uses `ArrayList`, the other uses a regular array. I wrote a simple test:
```java
public class MyBenchmark {
public static void main(String[] args) {
long start = System.nanoTime();
for (int i = 0; i < 100000; i++) {
// Code with ArrayList
List list = new ArrayList<>();
for (int j = 0; j < 1000; j++) {
list.add(j);
}
int sum = 0;
for (int val : list) {
sum += val;
}
}
long end = System.nanoTime();
System.out.println("ArrayList time: " + (end - start));
start = System.nanoTime();
No answers yet.
Log in to leave an answer