views:

473

answers:

2

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
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
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
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