We should always use StringBuilder append() method rather than String "+" operator to avoid cost.
Note that what "+" operator does is:
- create a new string;
- make a copy of the left string;
- 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