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 ?
Knowing that:
insert
at the end of the string representation is equivalent to an append
in term of time complexity (O(n)).insert
anywhere else than at the end can't be obtained with an append
(as they have differents purposes).insert
may involve up to 3 System.arraycopy
(native) calls, while an append
1.You can easily conclude:
append
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.
They have different functionalities and different complexities,
insert
:
Where append
:
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.
According to Java API docs. You must provide offset if you use insert.
StringBuilder.insert(5, "String");
but StringBuilder.append("string")
doesn't. I assume append has a better performance than insert.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.