The fact that the replace method returns a string object rather than replacing the contents of a given string is a little obtuse (but understandable when you know that strings are immutable in Java). I am taking a major performance hit by using a deeply nested replace in some code. Is there something I can replace it with that would make it faster?
All string manipulation in general are very slow. Consider to use StringBuffer, it's not exactly like the String class, but have a lot in common and it's mutable as well.
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
.
I agree with the above. Use StringBuffer for thread-safety and StringBuilder when working with single threads.
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.