views:

1104

answers:

4

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?

A: 

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.

Artem Barger
In general, if you don't need your buffer to be thread-safe (i.e. you don't have multiple threads manipulating the same buffer at once), you should use StringBuilder instead of StringBuffer.
Avi
From the StringBuffer documentation: The StringBuilder class should generally be used in preference to this one, as it supports all of the same operations but it is faster, as it performs no synchronization.
tgamblin
I used to work a lot of with multi-threaded environment so StringBuffer came in my mind naturally.
Artem Barger
Not sure why this question sparked a riot fest.
ojblass
+9  A: 

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.

paxdiablo
Also remember to use StringBuilder if you don't require thread safety, its generally faster and works the same.
Curtis Tasker
+2  A: 

I agree with the above. Use StringBuffer for thread-safety and StringBuilder when working with single threads.

Jeremy
+3  A: 

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.

David Nouls