Paul Lutus said:
This
is much faster:
String original = "This is my test string.";
String replacement = original.replaceAll("."," ");
System.out.println("[" + original + "]");
System.out.println("[" + replacement + "]");
System.out.println(original.length() - replecement.length());
Result:
[This is my test string.]
[ ]
0
Before the purists reply, remember -- the replaceAll() method is written in
native code, and "faster" was the criterion.
That's funny, I make your method 25x slower than my char[] one
That's strange. Because String is immutable, this:
str += " ";
has to be expanded to this:
str = newStringBuffer(str).append(" ").toString();
which creates two new objects every time round the loop.
Maybe the optimiser has figured out the redundant moves, moved a single
StringBuffer construction outside the loop (before) and a single
toString() outside the loop (after) and just left the append(" ") inside
the loop. That would explain the good performance, but it must be a pretty
clever optimiser. People do traditionally avoid string appends inside a
loop because of the poor preformance they usually get.
Steve.