Java Pattern Matcher:创建新的还是重置?

假设一个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重复使用它。