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?

serg
  • 109,619
  • 77
  • 317
  • 330

2 Answers2

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.

Kevin Montrose
  • 22,191
  • 9
  • 88
  • 137
  • 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. – AngerClown Aug 10 '09 at 13:48
-1

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

CharSequence veryBigString = new StringBuilder();
Pattern.compile(regex).matcher(veryBigString).replaceAll(replacement);
dfa
  • 114,442
  • 31
  • 189
  • 228
  • 1
    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? – Alan Moore Aug 09 '09 at 07:10