Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why Golang handle cutoff in atoi.go like this?

Tags:

go

overflow

atoi

// 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
}

I saw some code in file atoi.go of Golang package, why not write it like below?

var cutoff = maxUint64/uint64(base) + 1

Thanks a lot.

like image 204
littlec Avatar asked Nov 26 '25 09:11

littlec


1 Answers

I think the comment above the line you are referring to may answer your question:

// Use compile-time constants for common cases.

Because maxUint64/10 + 1 and maxUint64/16 + 1 only reference constants the compiler can calculate this. The result is that there is no need to perform the division operation at runtime every time ParseUint is called. You can see the benchmarks in the commit.

like image 120
Brits Avatar answered Nov 28 '25 01:11

Brits



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!