Why use useDelimiter(Pattern pattern) vs useDelimiter(String pattern)

174 views Asked by At

According the java:

public Scanner useDelimiter(String pattern) Sets this scanner's delimiting pattern to a pattern constructed from the specified String. An invocation of this method of the form useDelimiter(pattern) behaves in exactly the same way as the invocation useDelimiter(Pattern.compile(pattern)).

Is there any advantage to using Pattern.compile(pattern)? I have read that Pattern.compile(pattern) will place the compiled pattern in memory thereby making scanner searches faster. Will useDelimiter(String pattern) also place the pattern in memory?

In short, do they really behave exactly the same way?

1

There are 1 answers

1
neuronaut On

useDelimiter(String) may be even more efficient than useDelimiter(Pattern) because it not only compiles the pattern as with Pattern.compile(String) but it also caches up to 7 compiled patterns and simply looks them up. If you regularly use more than 7 patterns, though, you'll get caching churn which might degrade the performance and so you may be better off compiling and caching the patterns yourself.