Friday, 15 April 2016

Java Tutorial : Java String vs StringBuffer (performance difference)


Click here to watch in Youtube :
https://www.youtube.com/watch?v=uwot6R_DqUE&list=UUhwKlOVR041tngjerWxVccw

PerformanceTest.java
public class PerformanceTest
{

    /*
     * String is slow and consumes more memory when you
     * concat too many strings because every time it creates
     * new instance.
     */
    public static String concatWithString()
    {
        String str = "Welcome";
        for (int i = 0; i < 70000; i++)
        {
            str = str + "Peter";
        }
        return str;
    }

    /*
     * StringBuffer is fast and consumes less memory when
     * you cancat strings.
     */
    public static String concatWithStringBuffer()
    {
        StringBuffer sb = new StringBuffer("Welcome");
        for (int i = 0; i < 70000; i++)
        {
            sb.append("Peter");
        }
        return sb.toString();
    }

    public static void main(String[] args)
    {
        long startTime = System.currentTimeMillis();

        concatWithString();
        
        long  endTime = System.currentTimeMillis() - startTime;

        System.out.println("Time taken by Concating with String             : "
                + endTime + "ms");

        startTime = System.currentTimeMillis();

        concatWithStringBuffer();
        
        endTime = System.currentTimeMillis() - startTime;

        System.out.println("Time taken by Concating with StringBuffer       : "
                + endTime + "ms");

    }
}
Output
Time taken by Concating with String      : 15249ms
Time taken by Concating with StringBuffer: 10ms
Click the below link to download the code:
https://sites.google.com/site/javaee4321/java/StringBufferDemo_Perf_App.zip?attredirects=0&d=1

Github Link:
https://github.com/ramram43210/Java/tree/master/BasicJava/StringBufferDemo_Perf_App

Bitbucket Link:
https://bitbucket.org/ramram43210/java/src/c79bea5087cc43ffccd2a0b64318c83c53f07799/BasicJava/StringBufferDemo_Perf_App/?at=master

See also:
  • All JavaEE Viedos Playlist
  • All JavaEE Viedos
  • All JAVA EE Links
  • Servlets Tutorial
  • All Design Patterns Links
  • JDBC Tutorial
  • Java Collection Framework Tutorial
  • JAVA Tutorial
  • No comments:

    Post a Comment

    Google+ Followers

    Google+ Badge