Description
String.replaceAll(String, String)
compiles its first argument as a regular expression every time it is called. This can use a significant amount of time when parsing files even if the expression is relatively simple. A better way is to use Pattern.compile()
and store the result as a constant that will be reused.
Noncompliant code
public class MyClass {
public void extractData(final InputStream stream, final String name) {
try (InputStreamReader isr = new InputStreamReader(stream, StandardCharsets.UTF_8);
BufferedReader reader = new BufferedReader(isr)) {
for (String line = reader.readLine(); line != null; line = reader.readLine()) {
line.replaceAll(".", "");
}
} catch (IOException e) {
// catch the IOException
}
}
}
Compliant code
public class MyClass {
private static final Pattern pattern = Pattern.compile(".");
public void extractData(final InputStream stream, final String name) {
try (InputStreamReader isr = new InputStreamReader(stream, StandardCharsets.UTF_8);
BufferedReader reader = new BufferedReader(isr)) {
for (String line = reader.readLine(); line != null; line = reader.readLine()) {
pattern.matcher(line).replaceAll("");
}
} catch (IOException e) {
// catch the IOException
}
}
}
External reference
- Answer by coobird user in StackOverflow website: https://stackoverflow.com/questions/1466959/string-replaceall-vs-matcher-replaceall-performance-differences
Type
Code Smell
Tag
bad-practice
Kind regards,
Bryan