StringBuilder insert() vs append() performance?
They have different functionalities and different complexities,
insert
:
- (ensures The Capacity of the backing array, needs to copy the old one if necessary)
- pushes the elements leading the item at the insertion index (offset)
Where append
:
- (ensures The Capacity of the backing array, needs to copy the old one if necessary)
- 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.
Knowing that:
- An
insert
at the end of the string representation is equivalent to anappend
in term of time complexity (O(n)). - An
insert
anywhere else than at the end can't be obtained with anappend
(as they have differents purposes). - For info, an
insert
may involve up to 3System.arraycopy
(native) calls, while anappend
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.