6

Lets say I called replaceAll() on a big string that replaced 1,000 matching instances. Does it mean that 1,000 strings were created and reassigned in process because of string immutability? Is there any faster alternatives?

2 Answers 2

13

If you dig into String, you'll see that it delegates replaceAll() to Pattern & Matcher and Matcher.replaceAll() uses a StringBuilder to store the eventually returned value.

So no, String.replaceAll() does not create more than a small number of objects.

Sign up to request clarification or add additional context in comments.

1 Comment

Keep in mind that creating a new Pattern may be expensive. Depending on how often it's being called, it may be more efficient to create the Pattern once and create a Matcher from that. As always, profiling your app will tell you if this is necessary or a premature optimization.
-1

you can try with a StringBuffer/StringBuilder, since they are mutable CharSequences:

CharSequence veryBigString = new StringBuilder();
Pattern.compile(regex).matcher(veryBigString).replaceAll(replacement);

1 Comment

It doesn't matter if veryBigString is mutable; replaceAll() will still create a new StringBuffer to do the work, and return the result as a new String. Was that your point?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.