-
Notifications
You must be signed in to change notification settings - Fork 12.5k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
[libc] Optimize BigInt→decimal in IntegerToString
When IntegerToString converts a BigInt into decimal, it determines each digit by computing `n % 10` and then resets n to `n / 10`, until the number becomes zero. The div and mod operations are done using `BigInt::divide_unsigned`, which uses the simplest possible bit-by-bit iteration, which is a slow algorithm in general, but especially so if the divisor 10 must first be promoted to a BigInt the same size as the dividend. The effect is to make each division take quadratic time, so that the overall decimal conversion is cubic – and the division is quadratic in the number of _bits_, so the constant of proportionality is also large. In this patch I've provided custom code to extract decimal digits much faster, based on knowing that the divisor is always 10, and processing a word at a time. So each digit extraction is linear-time with a much smaller constant of proportionality. Full comments are in the code. The general strategy is to do the reduction mod 10 first to determine the output digit; then subtract it off, so that what's left is guaranteed to be an exact multiple of 10; and finally divide by 10 using modular-arithmetic techniques rather than reciprocal-approximation-based ordinary integer division. I didn't find any existing tests of IntegerToString on a BigInt, so I've added one.
- Loading branch information
1 parent
61f94eb
commit b9168b8
Showing
2 changed files
with
218 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters