Skip to content

to_chars.cpp, 2 digits at a time and avoiding reversal loop - #2781

Merged
lemire merged 1 commit into
simdjson:masterfrom
fior512:tochars_2attime
Jul 13, 2026
Merged

to_chars.cpp, 2 digits at a time and avoiding reversal loop#2781
lemire merged 1 commit into
simdjson:masterfrom
fior512:tochars_2attime

Conversation

@fior512

@fior512 fior512 commented Jul 11, 2026

Copy link
Copy Markdown
Contributor

Summary

This PR propose an improvement of src/to_chars::dragonbox() by using 2-at-a-time method (Alexandrescu, "Three Optimization Tips for C++", 2012) and back-to-front+memcpy write in buffer to avoid reversal loop. Reducing by 3x the number of loop iterations in this function.

Context

This PR continue:

Issues related to this PR:

100% on tests with:

cmake -B build -D SIMDJSON_DEVELOPER_MODE=ON
cmake --build build
ctest --test-dir build

benchmarked with benchmark/car_builder/benchmark_car_builder.cpp:

cmake -B build -D SIMDJSON_DEVELOPER_MODE=ON -D CMAKE_BUILD_TYPE=Release
cmake --build build --target benchmark_car_builder -j
./build/benchmark/car_builder/benchmark_car_builder

Bench

master:

Trial 1: string_builder:     1.21 ns  0.82 GB/s  5.24 GHz  6.35 cycles/char  23.39 ins./char  3.68 i/c
Trial 2: string_builder:     1.21 ns  0.82 GB/s  5.23 GHz  6.36 cycles/char  23.39 ins./char  3.68 i/c
Trial 3: string_builder:     1.21 ns  0.82 GB/s  5.25 GHz  6.37 cycles/char  23.38 ins./char  3.67 i/c

this PR:

Trial 1: string_builder:     0.95 ns  1.05 GB/s  5.23 GHz  4.98 cycles/char  17.03 ins./char  3.42 i/c
Trial 2: string_builder:     0.95 ns  1.05 GB/s  5.25 GHz  4.98 cycles/char  17.03 ins./char  3.42 i/c
Trial 3: string_builder:     0.95 ns  1.05 GB/s  5.23 GHz  4.97 cycles/char  17.03 ins./char  3.42 i/c

computed with:

  • AMD Ryzen 5 7600X (6cores)
  • CPU governor pinned to Performance

Notes

  • Latency of to_chars.cpp of this PR, over benchmark/car_builder/benchmark_car_builder.cpp, drop from 0.95 ns/char to 0.85 ns/char if merged with to_chars.cpp, fast path to avoid i128 emulation when possible #2780
  • No license needed for 2-at-a-time method; credit given inside to_chars.cpp::dragonbox() doc as comments.
  • tried jeaiii algorithm inside dragonbox() to avoid completly modulo and division but it become 0.02ns/char slower than this PR.

@lemire

lemire commented Jul 11, 2026

Copy link
Copy Markdown
Member

Running tests.

@lemire
lemire merged commit 209cb92 into simdjson:master Jul 13, 2026
112 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants