This compares several techniques for converting integers to decimal strings with an eye toward practical performance. It starts from the common snprintf approach, moves to a naive method that produces reversed digits by repeated division by 10 and then reverses the buffer, and then to an improved in-place approach that writes digits backward to avoid the reversal step. A handy buffer-size trick uses 3 * sizeof(int) to guarantee enough space for MAX_INT plus terminator. Replacing a table lookup with an arithmetic addition turned out slower; using a small lookup table for single digits yields about a 9% improvement over that change.
A faster method from Facebook uses a 200-character table containing the pairs "00" through "99" so the loop extracts two digits per division, halving division count and writing two bytes per iteration. That two-digit lookup produces roughly a 31% speedup over the single-digit-table variant in the author’s benchmarks on a Core i7-2640M 64-bit system; snprintf is much slower. Using a constant digit-length is consistently faster than a computed digits10() on that machine. The two-digit-table trick appears in multiple places historically, but unclear licensing for the Facebook code prevented direct reuse in the author’s project.
Summary generated by AI from the linked article. hn.today is not affiliated with Hacker News or Y Combinator.