I was attempting to create a faster version of String.equals() method and started by simply copying it. The result I found was quite confusing. When I ran the copy pasted versio
Why is the JVM version faster than it's copy-pasted version. Isn't it effectively the same?
Surprisingly, it isn't.
String comparison is such an ubiquitous operation that it is almost certainly the case that your JIT compiler has an intrinsic for String.equals()
. This means that the compiler knows how to generate specially-crafted machine code for comparing strings. This is done transparently to you, the programmer, when you use String.equals()
.
This would explain why String.equals()
is so much faster than your method, even if superficially they appear identical.
A quick search finds several bug reports that mention such an intrinsic in HotSpot. For example, 7041100 : The load in String.equals intrinsic executed before null check.
The relevant HotSpot source can be found here. The functions in question are:
848 Node* LibraryCallKit::make_string_method_node(int opcode, Node* str1, Node* cnt1, Node* str2, Node* cnt2) {
and
943 bool LibraryCallKit::inline_string_equals() {