String Builder’s Append Vs Insert

Lakshmanan Subbiah
2 min readFeb 28, 2021

Recently I had to solve a problem in which the string grows equally on both sides i.e the string will grow on either way character by character. As you have seen in my past blogs I prone to code in Java and to build a string in java we usually go for StringBuilder.

tip: String is immutable, so every concatenation creates a new instance of the string class. Its a very costly process while done on a massive scale.

Append method usually appends the character/string to the end of the string being built using StringBuilder. But as I aforementioned, I had a case where I have to add character/string to the beginning of the building String.

While scouring through the references to append characters in the beginning of string through StringBuilder I found One stack-overflow user mention an insert method present in StringBuilder class in java by default. But the same user mentioned that using this will cause the ultimate aim of using StringBuilder to sham. This intrigued me, So I started researching what they have been doing inside StringBuilder’s insert method that made it so bad.

Okay, what does the insert method has been doing?

On every insert the string builder will perform an array copy operation for the remaining data inside the character array and place the characters of String inside the string builders character array.

On the contrary, all that the append method does is copy the characters from string to string builder’s character array without any special operation.

The append method only performs the copy array operation when required of a length increase.

I have performed a custom implementation of StringBuilder, you can find it here.

On benchmarking the string Builder class I get the insert method takes 1700 milliseconds on average to perform 100000 inserts and append takes only 3 milliseconds to perform the same amount of appends.

#100DaysOfCode #Day10

--

--