Fastest way to convert numeric chars to int

Pepe Carval :

From looking over here and other websites I know there are two common ways to convert a numeric char value like '5' to an int value:

  1. Using Character.getNumericValue()

  2. Subtracting the number with the ASCII value for '0'; i.e. int number = num - '0', where num is a char value.

Which of these two approaches is the fastest and most efficient?

Stephen C :
  1. The two versions are not equivalent:

    • The Character.getNumericalValue(...) methods work for a variety of characters that represent digits or numbers, and it will return -1 or -2 in cases where the character doesn't represent a non-negative integer.
    • The num - '0' approach only gives the correct answer for the codepoints that correspond to the ASCII characters '0' through '9'. For all other codepoints or codeunits, it gives a meaningless value.
  2. The num - '0' version will be faster. This is clear from looking at the source code for getNumericalValue(...).

  3. While the difference is significant in relative terms, it is very small in absolute terms.


I concur with the comments that say that this is most likely a premature optimization.

It is also an incorrect optimization in some contexts.


I use it a lot so was wondering if I was using the most efficient one.

It is definitely premature optimization :-)

The number of times you write a particular code sequence is unrelated to the number of times the code sequence is executed. It is the latter that determines whether an optimization is worth the effort.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=163606&siteId=1