You can improve performance by using precompiled regular expressions. Under the hood String.replaceAll
is going to compile and apply a regular expression for you anyway. As compilation of the regexp is relatively computationally intensive, this should improve performance when executing this code frequently.
private static final Pattern PATTERN_1 = Pattern.compile("\u00f5");
private static final Pattern PATTERN_2 = Pattern.compile(Character.toString((char) 241));
String original = new String("A" + (char) 245 + "\u00f1" + "D");
String replaced2 = PATTERN_1.matcher(original).replaceAll("B");
replaced2 = PATTERN_2.matcher(replaced2).replaceAll("C");
System.out.println(original + " -> " + replaced2);
Will print out:
A??D -> ABCD
When working with a very very long String
this probably won't offer much performance over what you proposed.
As an aside:
Using non UTF-8 characters in code will cause you (and your colleagues) pain down the road. You should use Unicode characters or, as you were, character decimal representations at all times.