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;

/**
 * Note: to run this you will need a patched version of IntData that delivers correct results for
 * <code>stringSizeOfInt()</code>
 */
@State(Scope.Benchmark)
@Fork(3)
public class IsolatedIntData {

    private IntData[] intData;
    private char[] buf;

    @Setup
    public void setup() throws IOException {
        final var SIZE = 100_000;
        System.out.println("Creating " + SIZE + " IntData of 0..999_999");
        intData = new IntData[SIZE];
        for (int i = 0; i < SIZE; i++) {
            intData[i] = new IntData();
            intData[i].reset(RandomUtils.secure().randomInt(0, 1_000_000));
        }
        buf = new char[10];
    }

    @Benchmark
    public void intDataCharAt(Blackhole blackhole) {
        for (var data : intData) {
            for (int i = 0; i < data.length(); i++)
                buf[i] = data.charAt(i);  // isn't this kinda slow?
            blackhole.consume(buf);
        }
    }

    @Benchmark
    public void intDataGetChars(Blackhole blackhole) {
        for (var data : intData) {
            data.writeTo(buf, 0);
            blackhole.consume(buf);
        }
    }

    public static void main(String[] args) throws IOException {
        var test = new IsolatedIntData();
        test.setup();
        for (var data : test.intData) {
            for (int i = 0; i < data.length(); i++)
                test.buf[i] = data.charAt(i);  // isn't this kinda slow?
        }
    }
}


/*

IsolatedIntData.intDataCharAt    thrpt   15   223,689 ±  0,836  ops/s
IsolatedIntData.intDataGetChars  thrpt   15  1020,029 ± 21,783  ops/s

 */