Could someone tell me what is the correct way to b...
# getting-started
h
Could someone tell me what is the correct way to benchmark ArrayList.add(index, element) method with JMH? I made one like this but note sure if it’s the correct approach:
Copy code
@BenchmarkMode(Mode.AverageTime)
@Fork(2)
@Measurement(iterations = 10)
class MyBenchmark {
    @Benchmark
    fun testMethod(): Any {
        val list: List<Int> = ArrayList()
        for (i in 0 until NR_TO_INSERT) {
            list.add(list.size / 2, i)
        }
        return list
    }

    companion object {
        private const val NR_TO_INSERT = 500000
    }
}
h
Some time ago that i benchmarked sth but i think you want to move list instanciation out of the benchmarked method and instead of returning the list, you want a blackhole to consume it, if at all
j
Jmh does a bunch of rewriting to avoid dead code elimination, although I don't know specifically what that is. What are you trying to benchmark? it looks like you want to test inserting in the middle of the list. However calling size() is also a variable time operation (depending on the implementation!), so it might be better to keep track of that separately. What do you want to learn? Average time to run a variable difficulty thing (inserting into size 1 list, or inserting into size 10k list) might not mean very much
h
Sorry for late answer, I am benchmarking speed of “add” (concretely adding in the middle as you said) method on ArrayList.