简体   繁体   中英

Java String vs StringBuilder

As far as i know + operator in Java String is overloaded and while we are using + operator it automatically chooses StringBuffer or StringBuilder to concatenate strings with better performance. Only exception of this is while we are using + operator inside a loop. In this case Java doesn't use benefits of StringBuffer and StringBuilder. Is that true? I will concatenate 40 Strings (around 4500 chars) and I will repeat it so often so I wanted be sure about it.

No, Java will always (almost always, see comment bellow) convert concatenation into the StringBuilder . However the problem with loop is that it will create new instance of StringBuilder per each walkthrough.

So if you do String someString = i + "something"; inside the loop which goes from 0 to 1000 it will create for you new instance of StringBuilder 1000 times. Which could be a performance problem then. So just declare StringBuilder before the loop and then use it inside it.

  • String is immutable while StringBuilder is mutable it means when you create a String you can never change it

  • String is thread safe while StringBuilder not

  • String stores in Constant String Pool while StringBuilder in Heap

When you loop

oldString = oldString + somechars,

it means you create a new String and put oldString`s value into it first ,then append somechars ,then redirect the oldString variable to the result

What are Strings in Java?

Strings in Java are objects used to represent a sequence of character. They can be either created using the String Literal or by using the NEW keyword. Strings are immutable in Java are represented in the UTF-16 format. When a new String is created, it looks for the String with the same value in the JVM string pool. If it finds a same value, then it returns the reference else it created a String object and places that object in the String pool.

Apart from this, String uses the + operator to concatenate two strings and internally used the StringBuffer to perform this action.

What is String Builder in java?

String builder is used to create mutable string and growable in nature.It is not thread safe, that is why it is faster than string buffer .However when it comes to multithreading where is multiple threads try to access, in such case, one should go with string buffer.

It has two primary methods, append and insert.Append adds a character sequences at the end each time wheares insert put a specific set of characters at specified location. It automatically grows larger as and when internel buffer overflows.

Differences between String and String Builder

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM