⚡ Why Integer no longer stores its value as a String
#1050
LVMVRQUXL
announced in
Announcements
Replies: 0 comments
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
If you've used the experimental
Integertype from Kotools Types before 5.2.0, you may have noticed arithmetic getting slower as numbers grew larger. That wasn't your imagination — it came from howIntegerstored its value internally.🐛 The problem
Every
Integeroperation —+,-,*, comparisons, eventoString()— had to work with aStringrepresentation of the number. That means every single operation reparsed the digits from scratch before it could do any arithmetic, and re-serialized them back to aStringafterward:For a handful of small numbers this cost is invisible. For code that performs many operations on large integers, it adds up — and it's entirely avoidable, since the underlying value doesn't actually change shape between operations.
🤔 Why it happened
Stringwas a convenient first representation: printing anIntegeris free, and arbitrary precision comes for granted. But parsing and formatting are O(d) operations for a d-digit number. Doing that on every arithmetic call means the total cost of a chain of operations grows with both the number of operations and the number of digits. That's the case even though a proper big-integer representation only needs to pay the parsing/formatting cost once, at the boundary.✅ The fix: a real arbitrary-precision representation per platform
Integerfrom Kotools Types 5.2.0 delegates to whatever native arbitrary-precision integer type each platform already provides — or, where none exists, to a purpose-built implementation:java.lang.BigIntegerBigIntNone of these store digits as text. Arithmetic operates directly on the underlying numeric representation, with parsing and formatting only happening at the actual boundaries —
parse(),fromLong(), andtoString()— not on every+or*in between.As a side benefit, dropping the previous approach also let the library remove its only third-party runtime dependency on Kotlin/Native — one less dependency to audit and update.
Integeris annotated with@ExperimentalKotoolsTypesApiand will be stabilized in a future release.🛠️ Adding Kotools Types to your project
See the Installation section of the project's README for Gradle/Maven setup — this article was written against version
5.2.0.This API is
@ExperimentalKotoolsTypesApi, so opt in either per call-site with@OptIn(ExperimentalKotoolsTypesApi::class)or project-wide via the compiler argument:See also: GitHub, API reference
Read the 5.2.0 highlights roundup for the other changes shipped in this release.
💬 Discussion
Have you hit performance issues from string-based arbitrary-precision arithmetic in other libraries? How did you work around it?
All reactions