Assume a Regular Expression
, which, via a Java Matcher
object, is matched against a large number of strings:
String expression = ...; // The Regular Expression
Pattern pattern = Pattern.compile(expression);
String[] ALL_INPUT = ...; // The large number of strings to be matched
Matcher matcher; // Declare but not initialize a Matcher
for (String input:ALL_INPUT)
{
matcher = pattern.matcher(input); // Create a new Matcher
if (matcher.matches()) // Or whatever other matcher check
{
// Whatever processing
}
}
In the Java SE 6 JavaDoc for Matcher, one finds the option of reusing the same Matcher
object, via the reset(CharSequence)
method, which, as the source code shows, is a bit less expensive than creating a new Matcher
every time, i.e., unlike above, one could do:
String expression = ...; // The Regular Expression
Pattern pattern = Pattern.compile(expression);
String[] ALL_INPUT = ...; // The large number of strings to be matched
Matcher matcher = pattern.matcher(""); // Declare and initialize a matcher
for (String input:ALL_INPUT)
{
matcher.reset(input); // Reuse the same matcher
if (matcher.matches()) // Or whatever other matcher check
{
// Whatever processing
}
}
Should one use the reset(CharSequence)
pattern above, or should they prefer to initialize a new Matcher
object every time?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…