Предположим, 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 для 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
?