Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

StringBuilder insert() vs append() performance?

Is there any difference in the performance of insert() vs append() from StringBuilder class? I will be building plenty of short string as text identifiers and asked myself this question... Should I initialize SB with a separator and use insert + append or just append ?

like image 540
Palcente Avatar asked Nov 27 '15 11:11

Palcente


People also ask

What is time complexity of StringBuilder append?

It is O(1) when appending single characters. A StringBuilder is like an ArrayList. When you append a single item the cost is O(1).

How is StringBuilder more efficient?

Creating and initializing a new object is more expensive than appending a character to an buffer, so that is why string builder is faster, as a general rule, than string concatenation.

Why is StringBuilder faster?

String is immutable whereas StringBuffer and StringBuilder are mutable classes. StringBuffer is thread-safe and synchronized whereas StringBuilder is not. That's why StringBuilder is faster than StringBuffer.

Is StringBuilder less efficient or more efficient?

It means two threads can call the methods of StringBuilder simultaneously. StringBuffer is less efficient than StringBuilder. StringBuilder is more efficient than StringBuffer.


2 Answers

Knowing that:

  • An insert at the end of the string representation is equivalent to an append in term of time complexity (O(n)).
  • An insert anywhere else than at the end can't be obtained with an append (as they have differents purposes).
  • For info, an insert may involve up to 3 System.arraycopy (native) calls, while an append 1.

You can easily conclude:

  • If you want to insert at the end of the string representation, use append
  • Otherwise, use insert

Doing so, you will have the best performance. But again, these two methods serving two differents purposes (with the exception of inserting at the end), there is no real question here.

like image 127
Hey StackExchange Avatar answered Sep 17 '22 05:09

Hey StackExchange


They have different functionalities and different complexities,

insert:

  1. (ensures The Capacity of the backing array, needs to copy the old one if necessary)
  2. pushes the elements leading the item at the insertion index (offset)

Where append:

  1. (ensures The Capacity of the backing array, needs to copy the old one if necessary)
  2. adds the new element to the tail of the array

So if you want to always add to the tail, then the performance will be the same since insert will not push any elements.

So, I would use append, it is just cleaner.

like image 35
Sleiman Jneidi Avatar answered Sep 18 '22 05:09

Sleiman Jneidi