Can anyone beat the performance of my integer to std::string conversion code?
Problem:
Efficiently converting an integer into a std::string is a challenge that has sparked the creation of various methods. This article explores different approaches and invites submissions to compare their performance.
Methods:
Common methods include:
-
The "C way": Using a stringstream.
-
sprintf: Often recommended for performance.
-
Boost's lexical_cast: Has its own implementation that doesn't rely on stringstreams.
-
Ben's algorithms: Optimized for both desktop and embedded systems.
-
ltoa (non-standard): Widely available, but its use may be limited.
Rules:
Submissions should adhere to specific guidelines:
- Convert both signed and unsigned 32-bit integers into decimals.
- Produce output as a std::string.
- Ensure compatibility with threading and signals.
- Assume an ASCII character set.
- Handle INT_MIN correctly on a two's complement machine.
- Output should be identical to the canonical C version using a stringstream.
- Compile and execute on VC 2010 and g .
Results:
The winning submissions demonstrated significant performance improvements:
- Eugene Smith's code: 8 times faster than sprintf on g (http://ideone.com/0uhhX)
- Timo's code: 15 times faster than sprintf on Visual C (http://ideone.com/VpKO3)
The above is the detailed content of Can You Outperform This Integer-to-String Conversion Code?. For more information, please follow other related articles on the PHP Chinese website!