String vs String Builder

In most of the programming language String is immutable data structure.

When any string is initialized or created, memory is allocated in the heap memory and reference is attached to the variable which is located in Stack memory.

  String someString = "string ref0: This is sanjeev";
  String someString0 = new String("This is sanjeev");

Variable someString, and someString0 are holding a object reference which has reference to the value. When we contcat the strings, it creates a sequence of references. For example,

 someString = someString + " string ref1 : he is full stack software" + " string ref2: developer";

Now, someString variable is assigned a reference for fourth string object with "string ref3 : This is sanjeev string ref1: he is full stack software string ref2: developer". As the someString is combination of multiple string object in heap, it can sometimes cause the memory leak when any object is missed out from garbage collector.

Understanding all of that, we may not want to create different instance of immutable string object for simple concatenation. It looks simpler but, cause lots of memory usage.

With the stringbuilder, we can build the string by appending multiple string value on the same object reference.

       StringBuilder stringBuilder =  new StringBuilder("This is sanjeev");
       stringBuilder.append(" he is a full stack software");
       stringBuilder.append(" developer");
       String someString1 = stringBuilder.toString();


Comments