Java 模式匹配器:创建新的模式还是重置?
假设一个 ,它通过 Java 对象与大量字符串匹配:Regular Expression
Matcher
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
}
}
在Java SE 6 JavaDoc for Matcher中,人们可以通过该方法找到重用同一对象的选项,正如源代码所示,这比每次都创建新的对象便宜一些,也就是说,与上面不同,可以这样做: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