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

前端 未结 2 1457
长情又很酷
长情又很酷 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.

    0 讨论(0)
  • 2021-01-21 05:46

    There are a couple reasons that this is done. Being a long-time embedded developer, using tiny microcontrollers that sometimes didn't even have a multiplication and division instruction, I can tell you that this is significantly faster. The key here is that the multiplier is a constant. If you were multiplying two variables, you'd either need to use the slower multiply and divide operators or, if they didn't exist, perform multiplication using a loop with the add operator.

    0 讨论(0)
提交回复
热议问题