Why is String.equals() faster than itself?

前端 未结 3 2034
你的背包
你的背包 2021-02-04 05:42

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

3条回答
  •  我寻月下人不归
    2021-02-04 06:31

    As you know, JAVA truly is neither a compiler based nor interpreter based language. By this I mean is java uses both i.e. a compiler to convert source code into an intermediate form which is then interpreted at runtime.

    It marks the LoC (Line of Code) executed to know which part of the code is run more frequently. As soon as JAVA figures out a part of code running more than a given threshold, it marks it hot and sends this piece of code to the compiler on the fly for a better-optimized version to be run when asked for the next time. This is called JIT (Just in Time)

    Now, since both the code are exactly similar, JAVA HotSpot should have optimized both the methods exactly the same and hence same execution time. Sadly, this isn't the case.

    As soon as, JIT figures out equals() method is hot and is being called too frequently, it goes for a special optimization at the hardware level.
    Yes, There is an entirely new set of instructions created by Intel to speed up text processing code. This means, there is a separate instruction to make Strings.equals() method more faster than your copy-pasted equals method.

    Now the question is how does this happen. Well, this is simple, Whenever String.equals() is warm (i.e. used more often but not heavily) the compiler does the same optimization as with the copy-pasted method. But as the equal() method gets hot, JIT directly uses the new instruction set for string comparison and Hence fast execution.

提交回复
热议问题