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?
+10
A:
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
2009-08-09 00:15:41
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
2009-08-10 13:48:02
A:
you can try with a StringBuffer/StringBuilder, since they are mutable CharSequences:
CharSequence veryBigString = new StringBuilder();
Pattern.compile(regex).matcher(veryBigString).replaceAll(replacement);
dfa
2009-08-09 00:21:01
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
2009-08-09 07:10:09