Short answer
Although perhaps possible from a theoretical point of view, no; not at compile time, these are compiled again.
But Pattern
uses a Flyweight pattern, such that once a regex is compiled, it is stored in memory, so full compilation at runtime is not necessary.
Compile time
From a theoretical point of view, it is possible that the compiler will perform what is known as constant propagation and thus resolve the problem at compile time. This can be done given the methods you call are final (or the callee is known at compile time), etc.
If one however compiles your method and inspects the Java bytecode, it compiles to:
public static boolean checkRegex(java.lang.String, java.lang.String);
Code:
0: aload_1
1: ifnonnull 6
4: iconst_0
5: ireturn
6: aload_0
7: invokestatic #15 // Method java/util/regex/Pattern.compile:(Ljava/lang/String;)Ljava/util/regex/Pattern;
10: astore_2
11: aload_2
12: aload_1
13: invokevirtual #16 // Method java/util/regex/Pattern.matcher:(Ljava/lang/CharSequence;)Ljava/util/regex/Matcher;
16: astore_3
17: aload_3
18: invokevirtual #17 // Method java/util/regex/Matcher.matches:()Z
21: ireturn
public static void main(java.lang.String[]);
Code:
0: ldc #18 // String ^.+@.+\..+$
2: ldc #19 // String email@example.com
4: invokestatic #20 // Method checkRegex:(Ljava/lang/String;Ljava/lang/String;)Z
7: pop
...
As you can perhaps see, the methods are simply translated into Java byte code and the method is called with the two parameters.
Some compilers (mostly ones for functional and logic programming languages) allow program specialization: if a certain call is done with a constant, the compiler can create a copy of that method and resolve what is known at compile time. It is however a trade-off, since introducing a large number of specialized methods, will reduce in a large code base.
Flyweight pattern at runtime
If you dig into the Java bytecode of java.util.regex.Pattern
, you will see:
private static final HashMap<String, CharPropertyFactory> map;
static CharProperty charPropertyFor(String name) {
// <editor-fold defaultstate="collapsed" desc="Compiled Code">
/* 0: getstatic java/util/regex/Pattern$CharPropertyNames.map:Ljava/util/HashMap;
* 3: aload_0
* 4: invokevirtual java/util/HashMap.get:(Ljava/lang/Object;)Ljava/lang/Object;
* 7: checkcast java/util/regex/Pattern$CharPropertyNames$CharPropertyFactory
* 10: astore_1
* 11: aload_1
* 12: ifnonnull 19
* 15: aconst_null
* 16: goto 23
* 19: aload_1
* 20: invokevirtual java/util/regex/Pattern$CharPropertyNames$CharPropertyFactory.make:()Ljava/util/regex/Pattern$CharProperty;
* 23: areturn
* */
// </editor-fold>
}
Notice the HashMap
, so this means Pattern
stores fragments of the regex and their corresponding micro-DFA, this behavior is known as a Flyweight. This means you only compile the regex once. Evidently you will still have to perform lookups, so this is no free optimization, but it will definitely help.