hn.today

Integer to String Conversion (2014)

tia.mat.br25 points0 comments
Screenshot of Integer to String Conversion (2014)

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.

Read on tia.mat.br0 comments on Hacker News

Summary generated by AI from the linked article. hn.today is not affiliated with Hacker News or Y Combinator.

More in Programming

The End of Rationing

The End of Rationing

The end of engineering rationing has made building software cheaper and easier, shifting the industry from expensive R&D to low fixed costs and higher marginal costs. This change allows for more experimentation and innovation, leading to fundamentally different products and features. (sanketsaurav.com)

The daily digest

Today's best Hacker News stories, summarized and screenshotted, one email a day.