Reputation: 7309
I have the following code
public boolean matches(String word) {
Pattern p = Pattern.compile("\\w$");
Matcher m = p.matcher(word);
return m.find();
}
I want to know if the java compiler substitutes the Pattern.compile("\w$") phrase with an object, or creates the object every time the function is called.
How can i find out what java makes to my code?
Is there an eclipse plugin which shows this?
Upvotes: 0
Views: 88
Reputation: 200236
The Java compiler will simply emit an invokestatic
bytecode instruction against java.util.regex.Pattern.compile
. And indeed, this method will return a Pattern
object that your code then has at its disposal.
So what you really want to know is readily available in the source code of Pattern.compile
. If that method just returns a new Pattern
object, there will be no reuse with future calls. If you see that the object is being cached, then some reuse will happen.
So have a look at the source code of the Java version that is of your interest.
Upvotes: 1
Reputation: 11470
You only know for sure if you have a look at the Java Bytecode generated sine Java has a lot of optimizations build in already.
For Eclipse I knowBytecode Outline plugin to show the bytecode directly from eclipse. Maybe you need to search for some resources how to read the bytecolde probably but most of it is kinda easy like object creation or class calls.
Upvotes: 0
Reputation: 7854
To view the optimizations done by compiler, you can follow like this:
1)Compile your program
2)decompile your program using java decompilers available (can check in google) to generate the source code again
3)compare your source with the decompiled one.
That will give you enough idea...
as decompilers are not so smart (and there's no need either).
While viewing runtime optimizations are much more difficult.
Upvotes: 0
Reputation: 9609
According to the source code, it creates the object every time the function is called.
public static Pattern compile(String regex) {
return new Pattern(regex, 0);
}
Upvotes: 1
Reputation: 4634
compile
method creates new object Pattern
which is reused later.
From source code:
public static Pattern compile(String regex, int flags) {
return new Pattern(regex, flags);
}
Upvotes: 0