Might be a silly question: Does JIT do method inlining to original Java library methods?
e.g. If I have a function calling String.charAt
, would JIT inline charAt
for me (when it's called enough times), or it has to look up vtable every time calling charAt
?
A bit more context:
In a hot path, I am calling a function replaceFirstChar
:
public String replaceFirstChar(String stringVal){
if(stringVal.charAt(0) == 'z')
return "a" stringVal.subString(1);
return stringVal;
}
There's actually a boolean
variable startingWithZ
available that can tell the same as stringVal.charAt(0) == 'z'
. So another way for me to write replaceFirstChar
would be:
public String replaceFirstChar(boolean startingWithZ, String stringVal){
if(startingWithZ)
return "a" stringVal.subString(1);
return stringVal;
}
I'm thinking if JIT can inline charAt(index)
to turn it into value[index]
(with value
being String
's actual value container byte[] value
) so that when charAt
is called it doesn't need to go look up vtalbe, etc, then the first implementation (charAt) won't be much slower than the second, or even the same.
CodePudding user response:
Yes. Run a test program using these options and see for yourself: -XX: UnlockDiagnosticVMOptions -XX: PrintInlining
public static void main(String[] args) throws Exception {
while (true) {
for (var k : System.getProperties().keySet()) {
if (k instanceof String s && s.charAt(0) == '~') {
System.out.println(s);
}
}
}
}
...
@ 42 java.lang.String::charAt (25 bytes) inline (hot)
...