The documentation doesn't tell us what replace
will do if there's no matching substring, but looking at the current implementation in Oracle's version (Java 8):
public String replace(CharSequence target, CharSequence replacement) {
return Pattern.compile(target.toString(), Pattern.LITERAL).matcher(
this).replaceAll(Matcher.quoteReplacement(replacement.toString()));
}
...it does look like you avoid some work and in particular memory allocations (the matcher) if you check first.
Which isn't to say that there isn't likely a better way to approach those 22 replacements, probably by using a single regular expression with a character class ([âê]
and so on), compiling that regex once, and then using a single matcher in a loop, very roughly like this (inspired by this answer):
// You can do this part once somewhere if you want to
Pattern regex = Pattern.compile("[âê]");
// Then:
StringBuffer resultString = new StringBuffer();
Matcher regexMatcher = regex.matcher(translatedText);
while (regexMatcher.find()) {
String match = regexMatch.group();
String replacement;
switch (match) {
// ...various cases setting `replacement`
}
regexMatcher.appendReplacement(resultString, replacement);
}
regexMatcher.appendTail(resultString);
translatedText = resultString.toString();
or if you want to prematurely micro-optimize it (a failing of mine):
// You can do this part once somewhere if you want to
Pattern regex = Pattern.compile("[âê]");
// Then:
StringBuffer resultString = null;
Matcher regexMatcher = regex.matcher(translatedText);
while (regexMatcher.find()) {
if (resultString == null) {
resultString = new StringBuffer(translatedText.length() + 100);
}
String match = regexMatch.group();
String replacement;
switch (match) {
// ...various cases setting `replacement`
}
regexMatcher.appendReplacement(resultString, replacement);
}
if (resultString != null) {
regexMatcher.appendTail(resultString);
translatedText = resultString.toString();
}