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;

import java.io.IOException;

@State(Scope.Benchmark)
@Fork(3)
public class IsolatedStringBuilder {

//    @Param({"5", "20", "100"})
    private int length = 10;

    private StringBuilder[] strings;
    private char[] buf;

    @Setup
    public void setup() {
        final var SIZE = 100_000;
        System.out.println("Creating " + SIZE + " StringBuilders of length " + length);
        strings = new StringBuilder[SIZE];
        for (int i = 0; i < SIZE; i++) {
            strings[i] = new StringBuilder().append(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);
        }
    }
}


/*

Benchmark                       Mode  Cnt     Score    Error  Units
IsolatedStringBuilder.charAt    thrpt   15  1304,567 ± 56,170  ops/s
IsolatedStringBuilder.getChars  thrpt   15  2231,755 ± 67,601  ops/s

 */