Java 模式匹配器:创建新的还是重置?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11391337/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 04:54:21  来源:igfitidea点击:

Java Pattern Matcher: create new or reset?

javaregexresetmatcher

提问by PNS

Assume a Regular Expression, which, via a Java Matcherobject, is matched against a large number of strings:

假设 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
    }
}

In the Java SE 6 JavaDoc for Matcher, one finds the option of reusing the same Matcherobject, via the reset(CharSequence)method, which, as the source code shows, is a bit less expensive than creating a new Matcherevery time, i.e., unlike above, one could do:

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
    }
}

Should one use the reset(CharSequence)pattern above, or should they prefer to initialize a new Matcherobject every time?

应该使用reset(CharSequence)上面的模式,还是应该Matcher每次都初始化一个新对象?

回答by Marko Topolnik

By all means reuse the Matcher. The only good reason to create a new Matcheris to ensure thread-safety. That's why you don't make a public static Matcher m—in fact, that's the reason a separate, thread-safe Patternfactory object exists in the first place.

一定要重用Matcher. 创建 new 的唯一理由Matcher是确保线程安全。这就是为什么你不创建一个public static Matcher m——事实上,这就是一个单独的、线程安全的Pattern工厂对象首先存在的原因。

In every situation where you are sure there's only one user of Matcherat any point in time, it is OK to reuse it with reset.

在您确定Matcher在任何时间点只有一个用户的每种情况下,都可以将其与reset.