将数字字符转换为 int 的最快方法

Fastest way to convert numeric chars to int

通过查看此处和其他网站,我知道有两种常见的方法可以将数字 char 值(如 '5' 转换为 int 值:

  1. 使用Character.getNumericValue()

  2. 减去'0'的ASCII值;即 int number = num - '0',其中 num 是一个 char 值。

这两种方法中哪种方法最快、最有效?

嗯,Character.getNumericValue() 采用 Unicoderadixcase文化考虑:

 '0' ->  0 // Same as number - '0'
 '9' ->  9 // Same as number - '0'
 'A' -> 10 // Hexadecimal 0xA == 10
 'f' -> 15 // Hexadecimal 0xF == 15
 '³' ->  3 // Unicode superscript 3
 '⒇'-> 20 // Unicode enclosed alphanumeric 20 
 '۵' ->  5 // Persian digit 5
 '*' -> -1 // Doesn't have any corresponding integer value
 '⅚' -> -2 // Even if 5/6 fraction Unicode character is a number, it's not integer

number - '0'

只是两个 int 的减法。这就是为什么 Character.getNumericValue() 不可避免地 变慢 (几纳秒,是否值得优化?)。但是,请注意,在 'A', 'f', '³', '*' 等情况下,您将得到 错误的答案 number - '0' 代码。

  1. 两个版本不等价:

    • Character.getNumericalValue(...) 方法适用于代表数字或数字的各种字符,在字符不代表的情况下,它将 return -1-2 t代表一个非负整数。
    • num - '0' 方法仅给出对应于 ASCII 字符 '0''9' 的代码点的正确答案。对于所有其他代码点或代码单元,它给出了一个无意义的值。
  2. num - '0'版本会更快。通过查看 getNumericalValue(...).

    的源代码可以清楚地看到这一点
  3. 虽然相对而言差异很大,但绝对差异很小。


我同意评论说这很可能是过早优化。

它在某些情况下也是不正确优化。


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

这绝对是过早的优化:-)

编写特定代码序列的次数与执行时代码序列的性能无关。一段代码只有在执行它所花费的时间对您的整个应用程序产生重大影响时才值得优化。