【发布时间】:2012-07-08 15:10:27
【问题描述】:
假设Regular Expression,通过Java 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 中,人们可以通过reset(CharSequence) 方法找到重用相同Matcher 对象的选项,正如源代码所示,该方法比创建一个新的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 对象?
【问题讨论】:
-
无论如何都要重用
Matcher。创建新Matcher的唯一充分理由是确保线程安全。这就是你不创建public static Matcher m的原因——事实上,这就是首先存在一个单独的Pattern类的原因。 -
那么,对于单线程应用程序,即使是作为实例或类变量,或者对于在方法内创建 Matcher 对象的多线程应用程序,reset() 就可以了,是吗?跨度>
-
@MarkoTopolnik:我认为将正则表达式的编译与其应用程序分开是拥有
Pattern类的另一个好理由。 -
在任何情况下,如果您确定在任何时间点只有一个
Matcher用户,则可以将其与reset一起重复使用。 -
仅供参考,在 Java 1.5 的 java.util.regex.Matcher 类中引入了 reset() 方法和 reset(CharSequence) 方法,并且从那时起就存在了。