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
}
}
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
毎回新しいオブジェクトを初期化することを好む必要がありますか?