Monday, 21 April 2014

Speed test: String vs StringBuilder in JAVA

We compare String with StringBuilder, run this code and see yourself, example:


public class SpeedTest
{
    public static void main(String[] args)
    {
        final String SAMPLE = "The Quick Brown Fox Jumps Over The Lazy Dog.";
        final int COUNT = 5000;

        // string
        String str = "";
        long start = System.nanoTime();
        for (int i = 0; i < COUNT; i++)
            str += SAMPLE;
        long strTotal = System.nanoTime() - start;
        if (str.length() == 123)
            System.exit(0);

        // StringBuilder
        StringBuilder builder = new StringBuilder(SAMPLE.length() * COUNT);
        start = System.nanoTime();
        for (int i = 0; i < COUNT; i++)
            builder.append(SAMPLE);
        long sbTotal = System.nanoTime() - start;

        System.out.println("String total time: " + (strTotal / 1000000.0)
                + " ms");
        System.out.println("StringBuilder total time: " + (sbTotal / 1000000.0)
                + " ms");
        System.out.println("StringBuilder vs. String: " + (strTotal / sbTotal));
    }

}


If this little "code" helped you, please subscribe, like us on facebook, share it, or do whatever you want with it

Have a good one. M.L.