What javac does
instanceof patterns
No new instructions: the same instanceof, then a checkcast into a new local.
Pattern matching for instanceof (Java 16) adds no new instructions. o instanceof String s compiles to exactly what the old idiom does: an instanceof test, then a checkcast and a store into a new local variable.
The source
// min-release: 16
// instanceof with a pattern: the same instanceof, then a checkcast into a new local.
public class InstanceofPattern {
static int length(Object o) {
if (o instanceof String s && !s.isEmpty()) {
return s.length();
}
return -1;
}
static int oldStyle(Object o) {
if (o instanceof String) {
String s = (String) o;
return s.length();
}
return -1;
}
}Compiled by javac 25 with -g and --release 17 to 25. Where releases produce different bytecode, each version is shown.
What to look for
- Compare
length()witholdStyle(): the sameinstanceof,ifeq,checkcastandastore_1. - The
checkcastcannot fail, but it is still needed: it gives the value the type String for the verifier and for the calls that follow. && !s.isEmpty()is just another branch after the variable is bound.
InstanceofPattern.class
static int length(Object o)
static int oldStyle(Object o)
javac --release 17 to 25 (the same bytecode for every release)