Skip to content

Replace ipv4 inet_ntop with a handrolled function #367

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Feb 20, 2025
Merged

Replace ipv4 inet_ntop with a handrolled function #367

merged 4 commits into from
Feb 20, 2025

Conversation

kiroma
Copy link
Contributor

@kiroma kiroma commented Feb 20, 2025

toIp is a surprisingly hot function when used in Drogon, accounting for a grand 6% of total runtime when I measured it during my stress tests.
I've tried to make the new function as efficient and consistent as possible, avoiding allocations by abusing the small string optimization. The longest IPv4 address has a total of 15 characters which is just enough to fit in a small libstdc++ string.
To abuse this, I preallocated the string and performed the conversion inside of it with a helper function that does work unconditionally, which achieves really good throughput and low run to run variance.
This speeds up IP to string conversion by about 10x

-----------------------------------------------------
Benchmark           Time             CPU   Iterations
-----------------------------------------------------
iptos            9.22 ns         9.22 ns     75759258
ntop             93.3 ns         93.3 ns      7407629

@rbugajewski
Copy link
Collaborator

Thank you for your contribution to improving Drogon’s performance! I appreciate your work on this 🎉

kiroma and others added 2 commits February 20, 2025 12:33
For some reason gcc assumes that static constexpr array can be modified and does not attempt to zero init the string, reading from the array instead. Having the buffer be initialized in the function instead via a consteval seems to yield proper results.
MSVC just straight up doesn't understand static initialization and attempts to initialize the static buffer on every function call. Microsoft never fails to disappoint.
@an-tao an-tao merged commit f7a781f into an-tao:master Feb 20, 2025
33 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.

3 participants