
Untitled
By: a guest on
Jun 30th, 2012 | syntax:
None | size: 1.63 KB | hits: 11 | expires: Never
Difference between concatenating strings and using StringBuffer append
String s = "<span class="className">StaticContent</span>";
String s = "<span class="className">" +
ResourceBundleObject.getString("StaticContent.key") + "</span>";
StringBuilder sb = new StringBuilder();
sb.append("<span class="className">");
sb.append(ResourceBundleObject.getString("StaticContent.key"));
sb.append("</span>");
String s = sb.toString();
"a" + "b" + "c" + "d" // 4 Strings
"ab" // 1 String
"abc" // 1 String
"abcd" // 1 String
// 7 String instances in total (& in theory / worst case)
StringBuilder sb = new StringBuilder("a").append("b").append("c").append("d")
// 4 Strings, 1 StringBuilder
= 5 objects (in theory/worst case)
String result = "";
for (int i = 0; i < 100; i++)
result += "."; // Ouch - this should be done with StringBuilder
1. First One will create three Instance. // "" will create 2 temp instance , concat using + another instance
2. Second One wil create One Instance.
- the String class is an immutable class.
- It will never really change internally. When you use the operator
it actually do not change the string itself, but rather return a
new String.
- StringBuilder is more efficient as it is designed with no thread-safety in mind.
- Will appends to it the previous value of the string.
- if you are building long strings, then using StringBuilder
- no synchronization is performed.
- StringBuilder lacks some methods split,search