假设 a Regular Expression
,通过 JavaMatcher
对象与大量字符串匹配:
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
}
}
在用于 Matcher 的 Java SE 6 JavaDoc 中,可以通过该方法找到重用同一Matcher
对象的选项reset(CharSequence)
,如源代码所示,该方法比Matcher
每次都创建一个新对象要便宜一些,即,与上面不同,可以做:
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
}
}
应该使用reset(CharSequence)
上面的模式,还是应该更喜欢Matcher
每次都初始化一个新对象?