Welcome Message

"The difference between a successful person and others is not a lack of strength,
not a lack of knowledge, but rather a lack in will."
-Vince Lombardi

June 30, 2011

String and StringBuffer Implementation - which is fast

All,

 

    I came across some interesting fact on String and String Buffer. We know that String concatination internaly uses StringBuffer to do the concatination operation, and thinking about this we do concatination as mentioned below: 

        String str=a+b; a and b is string objects.

 

    java compiler compiles above code in this fashion:

 

        String str=(new StringBuffer()).append(a).append(b).toString());

 

    Above code creates two objects, and as you must be knowing that java maintains the string data in char array which is also an object so +1 more object. So in total 3 objects gets created for one concatination operation. Please note that object creation is one of the costiliest operation in java.

 

    I created one test program just to see the performance difference and results were dramatic... i ran both loop in same program 1 lakhs times. See the time difference... So based on below result i would recommend please start using StringBuffer.append whenever you are doing any concatination operation in java...

 

    time taken by string: 78080 (ms)
    time taken by String buffer: 31 (ms)

 

 

 

 

 

 

 

 

No comments:

Post a Comment

Thank you for your valuable comments.