Wednesday, April 22, 2015

String, Stringbuffer and StringBuilder in java basic knowledge Video

We should always use StringBuilder append() method rather than String "+" operator to avoid cost. 

Note that what "+" operator does is:
  1. create a new string;
  2. make a copy of the left string;
  3. append the right char/string to the end.

So, a series of "+" operation is O(n^2)-time, not O(n).
StringBuilder is smarter and you can think it as a dynamically resizing array of char.
No copies for append() and it can output a String by calling toString() method.

Note: StringBuilder has no synchronization, i.e. it is not thread-safe.
If synchronization is required, it is recommend to use StringBuffer.

http://sophie-notes.blogspot.com/2013/02/java-stringbuilder-vs-string.html

No comments:

Post a Comment

java - fill distinct objects in ArrayList

If you have a list that contains some objects that it is considered as duplication when two or three fields of these objects are equal. How ...