/*
 * Copyright 2008 Jeremias Maerki
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/* $Id$ */

package test;

import java.nio.CharBuffer;

public class CharBufferSpeedTest {

    private static final int STEPS = 20;

    public String runStringBuffer() {
        return runStringBuffer(16);
    }

    public String runStringBuffer(int initialCapacity) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < STEPS; i++) {
            sb.append(" myValue=").append(Integer.toString(i));
        }
        return sb.toString();
    }

    public String runCharBuffer() {
        CharBuffer buf = CharBuffer.allocate(1024);
        for (int i = 0; i < STEPS; i++) {
            buf.put(" myValue=").put(Integer.toString(i));
        }
        return buf.rewind().toString();
    }

    public static void main(String[] args) {
        try {
            CharBufferSpeedTest app = new CharBufferSpeedTest();

            //Warmup and verification
            String s1 = app.runStringBuffer();
            String s2 = app.runCharBuffer();
            assert s1.equals(s2);

            int RUNS = 1000000;

            //Run
            long start, duration;

            int FULL_RUNS = 3;

            for (int r = 0; r < FULL_RUNS; r++) {
                start = System.currentTimeMillis();
                for (int i = 0; i < RUNS; i++) {
                    app.runStringBuffer();
                }
                duration = System.currentTimeMillis() - start;
                System.out.println("StringBuffer def: " + duration + " ms");

                start = System.currentTimeMillis();
                for (int i = 0; i < RUNS; i++) {
                    app.runStringBuffer(1024);
                }
                duration = System.currentTimeMillis() - start;
                System.out.println("StringBuffer 1024: " + duration + " ms");

                start = System.currentTimeMillis();
                for (int i = 0; i < RUNS; i++) {
                    app.runCharBuffer();
                }
                duration = System.currentTimeMillis() - start;
                System.out.println("CharBuffer: " + duration + " ms");
            }


        } catch (Exception e) {
            e.printStackTrace();
            System.exit(1);
        }
    }

}
