Java getChars method in Integer class, why is it using bitwise operations instead of arithmetic?

前端 未结 2 1475
长情又很酷
长情又很酷 2021-01-21 05:19

So I was examining the Integer\'s class source code (JDK 8) to understand how an int get converted to a String. It seems to b

2条回答
  •  灰色年华
    2021-01-21 05:44

    I don't know the reason for this specific change and unless you find the original author, it's unlikely you'll find an authoritative answer to that anyway.

    But I'd like to respond to the wider point, which is that a lot of code in the runtime library (java.* and many internal packages) is optimized to a degree that would be very unusual (and I dare say irresponsible) to apply to "normal" application code.

    And that has basically two reasons:

    1. It's called a lot and in many different environment. Optimizing a method in your server to take 0.1% less CPU time when it's only executed 50 times per day on 3 servers each won't be worth the effort you put into it. If, however, you can make Integer.toString 0.1% faster for everyone who will ever execute it, then this can turn into a very big change indeed.
    2. If you optimize your application code on a specific VM then updating that VM to a newer version can easily undo your optimization, when the compiler decides to optimize differently. With code in java.* this is far less of an issue, because it is always shipped with the runtime that will run it. So if they introduce a compiler change that makes a given optimization no longer optimal, then they can change the code to match this.

    tl;dr java.* code is often optimized to an insane degree because it's worth it and they can know that it will actually work.

提交回复
热议问题