Compare the ArrayList with LinkedList on adding new objects

package com.demo;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;

@BenchmarkMode(Mode.AverageTime)
//@BenchmarkMode(Mode.SingleShotTime)
@OutputTimeUnit(TimeUnit.SECONDS)
@State(Scope.Benchmark)
@Fork(value = 2, jvmArgs = {"-Xms2G", "-Xmx2G"}) //clean JVM
//@Warmup(iterations = 10, time = 500, timeUnit = TimeUnit.MILLISECONDS)
//@Measurement(iterations = 10, time = 500, timeUnit = TimeUnit.MILLISECONDS)
public class BenchmarkList {
    public static void main(String[] args) throws RunnerException {

        Options opt = new OptionsBuilder()
                .include(BenchmarkList.class.getSimpleName())
                .warmupIterations(1)
                .measurementIterations(1)
                .build();

        new Runner(opt).run();
    }
    
    @State(Scope.Thread)
    public static class MyState {
        public int output = 100;
        List<String> arrayList = new ArrayList<>();
        List<String> linkedList = new LinkedList<>();
    }
    
    @Benchmark
    public void arrayList(MyState state) throws InterruptedException {
    	for(int i=0; i<state.output; i++) {
    		state.arrayList.add("Hello"+i);
    	}
    }
    
    @Benchmark
    public void linkList(MyState state) throws InterruptedException {
    	for(int i=0; i<state.output; i++) {
    		state.linkedList.add("Hello"+i);
    	}
    }
}

Output :

Leave a Comment