Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Faster alternatives to replace method in a Java String?

Tags:

java

replace

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?

like image 876
ojblass Avatar asked Jun 18 '09 05:06

ojblass


People also ask

How do you replace a word in a string in Java without using replace method?

To replace a character in a String, without using the replace() method, try the below logic. Let's say the following is our string. int pos = 7; char rep = 'p'; String res = str. substring(0, pos) + rep + str.

Is string replace costly in Java?

As you know, in Java, Strings are immutable. So every time we construct or concatenate a String object, Java creates a new String – this might be especially costly if done in a loop.

What is the difference between Replace () and replaceAll ()?

The only difference between them is that it replaces the sub-string with the given string for all the occurrences present in the string. Syntax: The syntax of the replaceAll() method is as follows: public String replaceAll(String str, String replacement)

How do you replace only one occurrence of a string in Java?

To replace the first occurrence of a character in Java, use the replaceFirst() method.


2 Answers

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.

like image 50
paxdiablo Avatar answered Sep 18 '22 21:09

paxdiablo


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.

like image 43
David Nouls Avatar answered Sep 20 '22 21:09

David Nouls