package org.glassfish.jaxb.runtime.v2.runtime.unmarshaller;

import org.apache.commons.lang3.RandomStringUtils;
import org.openjdk.jmh.annotations.*;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.infra.Blackhole;

@State(Scope.Benchmark)
@Fork(3)
public class IsolatedString {

//    @Param({"5", "20", "100"})
    private int length = 10;

    private String[] strings;
    private char[] buf;

    @Setup
    public void setup() {
        final var SIZE = 100_000;
        System.out.println("Creating " + SIZE + " strings of length " + length);
        strings = new String[SIZE];
        for (int i = 0; i < SIZE; i++) {
            strings[i] = RandomStringUtils.secure().next(length);
        }
        buf = new char[length];
    }

    @Benchmark
    public void stringCharAt(Blackhole blackhole) {
        for (var string : strings) {
            for (int i = 0; i < string.length(); i++)
                buf[i] = string.charAt(i);  // isn't this kinda slow?
            blackhole.consume(buf);
        }
    }

    @Benchmark
    public void stringGetChars(Blackhole blackhole) {
        for (var string : strings) {
            string.getChars(0, string.length(), buf, 0);
            blackhole.consume(buf);
        }
    }
}


/*

temurin 21.0.5+11-LTS, 100_000 strings of length 10
Benchmark                 Mode  Cnt     Score     Error  Units
Isolated.stringCharAt    thrpt   15  1108,888 ±  51,021  ops/s
Isolated.stringGetChars  thrpt   15  2063,215 ± 116,811  ops/s

 */