Last active
October 24, 2021 08:36
-
-
Save renatoathaydes/a18fcd509115df66efecb1b9cfcc6dc9 to your computer and use it in GitHub Desktop.
Using static variables in local scope in Java.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import java.util.regex.Pattern; | |
| public class Test { | |
| public static void main(String[] args) { | |
| check("a"); | |
| check("b"); | |
| } | |
| static Pattern compile(String pattern) { | |
| System.out.println("compile(" + pattern + ")"); | |
| return Pattern.compile(pattern); | |
| } | |
| static void check(String string) { | |
| // Compiling the pattern only once: Good | |
| // Keeping the pattern local to the method: Good | |
| // Capturing scope: Egh... | |
| var patterns = new Object() { | |
| static final Pattern P_CHECK = compile("a"); | |
| }; | |
| System.out.println("check(" + string + "): " | |
| + patterns.P_CHECK.matcher(string).find()); | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import java.util.regex.Pattern; | |
| public class Test { | |
| public static void main(String[] args) { | |
| check("a"); | |
| check("b"); | |
| } | |
| static Pattern compile(String pattern) { | |
| System.out.println("compile(" + pattern + ")"); | |
| return Pattern.compile(pattern); | |
| } | |
| static void check(String string) { | |
| // Compiling the pattern only once: Good | |
| // Keeping the pattern local to the method: Good | |
| // Does not capture the scope: Good | |
| class Patterns { | |
| static final Pattern P_CHECK = compile("a"); | |
| } | |
| System.out.println("check(" + string + "): " | |
| + Patterns.P_CHECK.matcher(string).find()); | |
| } | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Bytcode of the first version:
The generated class
Test$1is identical to theTest$Patternsclass, but thecheckimplementation is unnecessarily creating a new instance ofTest$1, resulting in 8 extra, unnecessary bytecode instructions.