Faster alternatives to replace method in a Java String?
The previous posts are right, StringBuilder/StringBuffer are a solution.
But, you also have to question if it is a good idea to do the replace on big Strings in memory.
I often have String manipulations that are implemented as a stream, so instead of replacing it in the string and then sending it to an OutputStream, I do the replace at the moment that I send the String to the outputstream. That works much faster than any replace.
This works much faster if you want this replace to implement a template mechanism. Streaming is always faster since you consume less memory and if the clients is slow, you only need to generate at a slow pace - so it scales much better.
This is what StringBuilder is meant for. If you're going to be doing a lot of manipulation, do it on a StringBuilder
, then turn that into a String
whenever you need to.
StringBuilder
is described thus:
"A mutable sequence of characters. This class provides an API compatible with StringBuffer, but with no guarantee of synchronization".
It has replace
(and append
, insert
, delete
, et al) and you can use toString
to morph it into a real String
.