Integer-to-String Conversion: std::to_string vs std::to_chars
Question 41 / 51 • Correct so far: 0 (0 answered)
To String
long long convertAll(const std::vector<int>& nums) {
long long total = 0;
for (int n : nums) {
std::string s = std::to_string(n);
total += static_cast<long long>(s.size());
}
return total;
}
long long result = convertAll(NUMBERS); To Chars
long long convertAll(const std::vector<int>& nums) {
long long total = 0;
char buf[32];
for (int n : nums) {
auto [end, _] = std::to_chars(buf, buf + sizeof(buf), n);
total += static_cast<long long>(end - buf);
}
return total;
}
long long result = convertAll(NUMBERS); Shared test data (shared-setup)
static const std::vector<int> NUMBERS = []() {
std::vector<int> v;
v.reserve(1000);
for (int i = 0; i < 1000; ++i)
v.push_back(i * 31 + 7);
return v;
}(); Which snippet is faster?
Snippet B is faster. std::to_string performs a locale-aware conversion and returns a heap-allocated std::string on every call. std::to_chars writes into a caller-supplied stack buffer with no locale lookup and no allocation.
Benchmark results
| Snippet | CPU time / iteration | Speedup |
|---|---|---|
| To Chars | 2.48 us | 1.9× |
| To String | 4.71 us | 1.0× |
Explore the source
Open in Compiler ExplorerQuiz complete. You can return to the question list to restart and compare.