public class BenchmarkPolluted {
    private String string = new String(new char[3152]);
    private StringBuilder stringBuilder = new StringBuilder(string);
    
    public int testString() {
        String sequence = this.string;
        int sum = 0;
        for (int i=0, j=sequence.length(); i<j; ++i) {
            sum += sequence.charAt(i);
        }
        return sum;
    }

    public int testStringBuilder() {
        StringBuilder sequence = this.stringBuilder;
        int sum = 0;
        for (int i=0, j=sequence.length(); i<j; ++i) {
            sum += sequence.charAt(i);
        }
        return sum;
    }

    public static void main(String[] args) {
        int res = 0;

        String s = "abcdefg";
        StringBuilder sB = new StringBuilder(s);
        for (int i = 0; i < 100_000; ++i) {
            try {
                res += s.charAt(i);
            } catch (Exception e) {
                // Expected
            }
            try {
                res += sB.charAt(i);
            } catch (Exception e) {
                // Expected
            }
        }

        BenchmarkPolluted b = new BenchmarkPolluted();
        long start = System.nanoTime();
        for (int i = 0; i < 1_000_000; ++i) {
            b.testString();   
        }
        long duration = System.nanoTime() - start;
        System.out.println("testString() took " + duration / 1_000_000 + " ms");

        start = System.nanoTime();
        for (int i = 0; i < 1_000_000; ++i) {
            b.testStringBuilder();
        }
        duration = System.nanoTime() - start;
        System.out.println("testStringBuilder() took " + duration / 1_000_000 + " ms");
    }
}
