Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Jun 30th, 2012  |  syntax: None  |  size: 1.63 KB  |  hits: 11  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. Difference between concatenating strings and using StringBuffer append
  2. String s = "<span class="className">StaticContent</span>";
  3.        
  4. String s = "<span class="className">" +
  5.            ResourceBundleObject.getString("StaticContent.key") + "</span>";
  6.        
  7. StringBuilder sb = new StringBuilder();
  8. sb.append("<span class="className">");
  9. sb.append(ResourceBundleObject.getString("StaticContent.key"));
  10. sb.append("</span>");
  11. String s = sb.toString();
  12.        
  13. "a" + "b" + "c" + "d"      // 4 Strings
  14. "ab"                       // 1 String
  15. "abc"                      // 1 String
  16. "abcd"                     // 1 String
  17.                            // 7 String instances in total (& in theory / worst case)
  18.        
  19. StringBuilder sb = new StringBuilder("a").append("b").append("c").append("d")
  20.                            // 4 Strings, 1 StringBuilder
  21.                                = 5 objects (in theory/worst case)
  22.        
  23. String result = "";
  24.  for (int i = 0; i < 100; i++)
  25.    result += ".";    // Ouch - this should be done with StringBuilder
  26.        
  27. 1. First One will create three Instance.  // "" will create 2 temp instance , concat using + another instance
  28.  2. Second One wil create One Instance.
  29.  
  30.  - the String class is an immutable class.
  31.  - It will never really change internally. When you use the operator
  32.    it actually  do not change the string itself, but rather return a
  33.    new String.
  34.  
  35.  - StringBuilder is more efficient as it is designed with no thread-safety in mind.
  36.  - Will appends to it the previous value of the string.
  37.  - if you are building long strings, then using StringBuilder
  38.  - no synchronization is performed.
  39.  - StringBuilder lacks some methods split,search