为什么Golang在atoi.go中处理截断时会这样做?

3
// code in atoi.go, line 90
var cutoff uint64
switch base {
case 10:
    cutoff = maxUint64/10 + 1
case 16:
    cutoff = maxUint64/16 + 1
default:
    cutoff = maxUint64/uint64(base) + 1
}

我在Golang包的文件atoi.go中看到了一些代码,为什么不像下面这样写呢?

var cutoff = maxUint64/uint64(base) + 1

非常感谢。

它在(迄今为止)最常见的用途中更快。 - AJR
1个回答

6

我认为你所指的那一行上方的注释可能已经回答了你的问题:

// 对于常见的情况使用编译时常量。

因为 maxUint64/10 + 1maxUint64/16 + 1 只涉及常量,编译器可以计算这些值。结果是每次调用 ParseUint 时无需在运行时执行除法操作。你可以在提交记录中查看基准测试结果。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接