top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

StringBuffer vs String

+4 votes
383 views

I was asked a question. If you had to build an XML structure as text, would you use StringBuffer or String? I thought String is more efficient that StringBuffer, but some of my friends say StringBuffer is more efficient than String.

I assume, that StringBuffer is a class, where as String is a base datatype and StringBuffer would have some easy (wrapper) methods for String. So, it is an add-on to string. Which should make StringBuffer heavier than String. Then how come using StringBuffer better than String?

posted Jun 14, 2016 by Akshay

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

+1 vote
 
Best answer

Your statement would have been true if the StringBuffer simply contains a string property and appends the value as string.
But that is not the case, basically there are two basic types/categories of objects based on their memory allocation behavior - Mutable and Immutable.

String is Immutable, which means every time you make a modification / concatenate text with existing text. The object is created newly by assigning new memory address and that is a very costly process.

Whereas StringBuffer on the other hand is Mutable, because of that the object is not created every time append is called.

Hope this helps.

answer Jun 20, 2016 by Vinod Kumar K V
...