/*
 * [TestArraycopySpeed.java]
 *
 * Summary: Test speed of arraycopy.
 *
 * Copyright: (c) 2013-2017 Roedy Green, Canadian Mind Products, http://mindprod.com
 *
 * Licence: This software may be copied and used freely for any purpose but military.
 *          http://mindprod.com/contact/nonmil.html
 *
 * Requires: JDK 1.8+
 *
 * Created with: JetBrains IntelliJ IDEA IDE http://www.jetbrains.com/idea/
 *
 * Version History:
 *  1.0 2013-04-19 initial version
 */
package com.mindprod.example;

import static java.lang.System.*;

/**
 * Test speed of arraycopy.
 *
 * @author Roedy Green, Canadian Mind Products
 * @version 1.0 2013-04-19 initial version
 * @since 2013-04-19
 */
public final class TestArraycopySpeed
    {
    /**
     * how many chars to copy in each test
     */
    private static int LIMIT = 10000;

    /**
     * Sample code compare String copy two different ways.
     *
     * @param args not used.
     *
     * @noinspection ManualArrayCopy
     */
    public static void main( String[] args )
        {
        // create an array of 9 Strings
        char[] source = new char[ LIMIT ];
        char[] target = new char[ LIMIT ];
        for ( int i = 0; i < LIMIT; i++ )
            {
            source[ i ] = ( char ) i;
            target[ i ] = ( char ) i;
            }
        int offset = 0;
        // test speed with various lengths of chunk to copy.
        for ( int chunk = 1; chunk < LIMIT; chunk++ )
            {
            // copy LIMIT chars chunk chars at a time with arrayCopy
            long p1 = System.nanoTime();
            offset = 0;
            for ( int j = 0; j < LIMIT / chunk; j++ )
                {
                System.arraycopy( source, 0, target, offset, chunk );
                offset += chunk;
                }
            // copy LIMIT chars chunk chars at a time with explicit loop
            long p2 = System.nanoTime();
            offset = 0;
            for ( int j = 0; j < LIMIT / chunk; j++ )
                {
                for ( int i = 0; i < chunk; i++ )
                    {
                    target[ offset++ ] = source[ i ];
                    }
                }
            long p3 = System.nanoTime();
            out.println( "chunksize: " + chunk + " arraycopy: " + ( p2 - p1 ) + " char by char: " + ( p3 - p2 ) );
            // we discover char by char is faster only for 1 and 2-character copies.
            }
        }
    }