package org.glassfish.jaxb.runtime.v2.runtime.unmarshaller;

import org.apache.commons.lang3.RandomUtils;
import org.openjdk.jmh.annotations.*;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.infra.Blackhole;

import java.io.IOException;

@State(Scope.Benchmark)
@Fork(3)
public class IsolatedIntArrayData {

    private IntArrayData[] intArrayData;
    private char[] buf;

    @Setup
    public void setup() throws IOException {
        final var OUTER_SIZE = 100_000;
        final var INNER_SIZE = 10;
        System.out.println("Creating " + OUTER_SIZE + " IntArrayData with " + INNER_SIZE + " ints of 0..999_999");
        intArrayData = new IntArrayData[OUTER_SIZE];
        for (int outer = 0; outer < OUTER_SIZE; outer++) {
            int[] ints = new int[INNER_SIZE];
            for (int inner = 0; inner < INNER_SIZE; inner++) {
                ints[inner] = RandomUtils.secure().randomInt(0, 1_000_000);
            }
            intArrayData[outer] = new IntArrayData();
            intArrayData[outer].set(ints, 0, INNER_SIZE);
            intArrayData[outer].length();
        }
        buf = new char[100];
    }

    @Benchmark
    public void intArrayCharAt(Blackhole blackhole) {
        for (var data : intArrayData) {
            for (int i = 0; i < data.length(); i++)
                buf[i] = data.charAt(i);  // isn't this kinda slow?
            blackhole.consume(buf);
        }
    }

    @Benchmark
    public void intArrayWriteTo(Blackhole blackhole) {
        for (var data : intArrayData) {
            data.writeTo(buf, 0);
            blackhole.consume(buf);
        }
    }
}


/*

with a single IntArrayData (not good approach, speedup is skewed by constant factors)
Benchmark                              Mode  Cnt         Score         Error  Units
IsolatedIntArrayData.intArrayCharAt   thrpt   15  85888294,441 ± 2359727,336  ops/s
IsolatedIntArrayData.intArrayWriteTo  thrpt   15  93751403,476 ±  772306,405  ops/s

with 100_000 IntArrayData (weird that the speedup is so high!)
Benchmark                              Mode  Cnt    Score    Error  Units
IsolatedIntArrayData.intArrayCharAt   thrpt   15   49,950 ±  0,590  ops/s
IsolatedIntArrayData.intArrayWriteTo  thrpt   15  537,718 ± 14,146  ops/s

 */