savi-lang / savi

A fast language for programmers who are passionate about their craft.
BSD 3-Clause "New" or "Revised" License
155 stars 12 forks source link

Refactor Integer.Format.Decimal to avoid internal array allocation. #357

Closed jemc closed 1 year ago

jemc commented 1 year ago

This new approach uses some bit magic to closely estimate digit count, and a lookup table to quickly get the divisor for a given digit count.

mneumann commented 1 year ago

another approach could be to first convert the integer into a BCD (Binary Coded Decimal). a U64 can hold 16 decimal digits in packed format, so you'd need at least two U64 to hold all possible decimals of a U64.

The BCD can then very efficiently converted to ASCII digits.

The nice thing, you can convert the number from right to left, starting with the tenth, hundreds etc.

See this gist:

https://gist.github.com/mneumann/a34c1823f89cfd18cd49eeae89d46ccf

It does not require table lookups, but two loops.

mneumann commented 1 year ago

That would only use registers and only one "division by 10" per digit, instead of 3. Though, you probably would not notice that :)

jemc commented 1 year ago

Makes sense - let's continue on that path in #358