logo-tera
logo-tera

Java: String vs StringBuilder vs StringBuffer

  • Agile
  • Software Development

01 March 2018

Share
facebookfacebookfacebook
banner

In application development it’s always important not leaving any details behind, that´s why we will focus today on analyzing the advantages and disadvantages of each of the classes that the Java ecosystem has to handle and manipulating Strings.

String

In Java the String object is immutable, this means that once you create it, it cannot be changed (ie: if we contact two Strings we are creating two separate String in a Heap and the garbage collector must release all the instances (fragments) we used to create the final String).

String salute = “Hi ” + ” my ” + ” name ” + “ is ”; 

Also, it’s important to emphasize that all the Strings we create without using a “new”, are stored in a pool of strings which is part of the Heap.

StringBuilder

StringBuilder is mutable and when you concatenate several Strings these are created in a Heap and not in the **pool of strings **saving the JVM (Java Virtual Machine) memory and reducing garbage collection time, for that reason it’s a good way to use and manipulate Strings.

StringBuffer

StringBuffer has the same functionality of the StringBuilder with the difference that all the methods of the StringBuffer are synchronized allowing them to be thread-safe. They should be considered for distributed environments or for situations where more than one Thread needs to manipulate the same strings.

StringBuilder salute = new StringBuilder(“Hi ”).append(“ my ”).append.(” name ”).append(“ is ”);

Note that we use the “same reference” of memory.

Comparison

ComparisonStringStringBuilderStringBuffer

Immutable

YesNoNo

Performance

FastFastSlow

Thread Safe

YesNoYes

Store

String PoolHeapHeap

 

Performance of String concatenation

We tested this sample code 10 times to see how it behaves from the memory perspective and how much time it takes to each one of the 3 classes to execute it. You can download the source code from this repository: https://github.com/erendontech/performance-string-comparison.git

Public class PerformanceStringComparison {

  private static final int MEGA_BYTES = 10241024;

  private static final int TIMES = 9999;

  public static void main(String args[]){

  PerformanceStringComparison msg = new

PerformanceStringComparison();

  msg.concatMultipleString(TIMES);

  msg.concatMultipleStringBuilder(TIMES);

  msg.concatMultipleStringBuffer(TIMES);

}

public void concatMultipleString(long _limit){

      System.out.println("Init concatMultipleString");

      System.gc();

      long start, end;       start = System.currentTimeMillis();

      String message = new String();

     for(int i = 0; i <= _limit; i++){         message = message + "Performance " + i;

      if(i == _limit){         Runtime rt = Runtime.getRuntime();         long usedMB = (rt.totalMemory()/MEGA_BYTES - rt.freeMemory()/MEGA_BYTES);         System.out.println(String.format("Memory usage: %s", usedMB));

        } }

      end = System.currentTimeMillis();       System.out.println(String.format("Time String %s milliseconds ", (end-start)));

}

public void concatMultipleStringBuilder(long _limit){

      System.out.println("Init concatMultipleStringBuilder");       System.gc();       long start, end;       start = System.currentTimeMillis();       StringBuilder message = new StringBuilder();

     for(int i = 0; i <= _limit; i++){          message.append("Performance ").append(i);          if(i == _limit){              Runtime rt = Runtime.getRuntime();              long usedMB = (rt.totalMemory() - rt.freeMemory()) / 1024 / 1024;              System.out.println(String.format("Memory usage: %s", usedMB));      } }

      end = System.currentTimeMillis()       System.out.println(String.format("Time StringBuilder %s milliseconds ", (end-start)));

}

public void concatMultipleStringBuffer(long _limit){

      System.out.println("Init concatMultipleStringBuffer");       System.gc();       long start, end;       start = System.currentTimeMillis();       StringBuffer message = new StringBuffer();

      for(int i = 0; i <= _limit; i++){          message.append("Performance ").append(i);          if(i == _limit){             Runtime rt = Runtime.getRuntime();             long usedMB = (rt.totalMemory() - rt.freeMemory()) / 1024 / 1024;              System.out.println(String.format("Memory usage: %s", usedMB));

        }

}

      end = System.currentTimeMillis();       System.out.println(String.format("Time StringBuffer %s milliseconds", (end-start)));

       }

}

 Avg (ms)Avg(memory user MB)

String

1116.531.4

StringBuilder

1.31

StringBuffer Safe

2.91

These results don’t necessarily mean that a class is better than the other; it just means that depending on the application you’re developing, the problem that you’re resolving and the environment/architecture where the application will run, you should choose the option that better fits your needs.

  • Application Development

Related Articles

  • Business
  • Agile
  • Software Development

Hiring Dev Professionals | Teravision Technologies

17 June 2024
cards-img-web
  • Agile
  • Mobile App Development
  • Software Development
  • Startups

5 cool Healthcare apps to check out while you envision yours

17 April 2024
cards-img-web
  • Agile
  • Digital Agencies
  • Software Development
  • Software Outsourcing

3 Tips for Marketing Agencies and Their Dedicated Software Development Team.

01 April 2024
cards-img-web
Let's
build
together

SET UP A DISCOVERY CALL WITH US TODAY AND accelerate your product development process by leveraging our 20+ years of technical experience and our industry-leading capability for quick deployment of teams with the right talents for the job.