It was an interview question. I was asked to implement the StringBuffer
append function. I saw the code after the interview. But I cannot understand how the operati
tl;dr: In simple words, each string concatenation expression using the +
character leads to a new String
object with the contents of the initial strings being copied to the new one. StringBuffer
holds an internal structure that expands only when needed, that characters are appended to it.
Hey, but lots of people use the +
string concatenation!
Well, we/they shouldn't.
In terms of memory usage, you are using an array in StringBuffer
in order to hold the characters - that resizes, truth, but rarely if the algorithm applied in resizing is efficient, and only one String
object that is created once toString()
is called, much better than the creation of a new String
object on each +
concatenation.
In terms of time complexity, characters are copied only once from _chars
to the new string (O(n)
time complexity), which in general is must better than string concatenation using the +
operator, on which each operation leads to a new copy of the characters to a new object, leading to O(1 + 2 + .... + n) = O(n^2)
operations.
Should I implement one on my own?
It would be good for you in terms of excercise, but modern languages provide native StringBuffer
implementations to use it in production code.
In four simple steps:
MyCustomStringBuilder
class that internally (privately) holds an array (let's name it _chars
) of characters of a fixed initial size. This array will hold
the string characters._chars
once
the holding string character length exceeds its length. (What you
are practically doing, is implementing a simple version of an
ArrayList
internally).stringBufferInstance.append(String s)
method, add
characters to _chars
, increasing its size if needed.In your toString()
method implementation, you can simply create a string using the array:
public String toString() {
return new String(_chars);
}