Thursday, March 28, 2013

Prefer StringBuilder to StringBuffer when thread safety is not a concern

NOTE THIS!!!!!!
One main difference between StringBuffer and StringBuilder is thread safety. Thread safety is not guaranteed by StringBuilder operations(append, insert ...). This is a main and huge difference between  StringBuilder and StringBuffer.

In my experience I have seen many developers using StringBuffer even when thread safety is not an issue. Using StringBuilder instead will be much faster and effective.

5 comments:

  1. string objects are immutable o.k .what is the reason to make a string object as immutable? plz clarify my doubt.

    ReplyDelete
    Replies
    1. That is a very good question. One main reason which I believe the makers of String class went ahead with immutable decision is thread safety. It is always a good practice to maintain immutability for objects which are heavily used in an application.

      Delete
    2. Another reason would be to support string pooling. Hope I answered your question. If not let me know I will walk you through an example

      Delete
  2. another medium quality reason is that as string is immutable the hash can be computed only once , and use many ,
    it guaranty correct performance

    ReplyDelete
  3. Do you have any Benchmark of the 2 usages StringBuffer / StringBuilder ?

    ReplyDelete