From 703593ab2a955f16aa521f61c8eef2f39cef6693 Mon Sep 17 00:00:00 2001 From: Anna Henningsen Date: Sat, 29 Jan 2022 22:20:10 +0100 Subject: [PATCH] src: reserve string allocation space early in URL::SerializeURL MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This can be useful for performance when doing many string concatenations. PR-URL: https://github.com/nodejs/node/pull/41759 Reviewed-By: Benjamin Gruenbaum Reviewed-By: Tiancheng "Timothy" Gu Reviewed-By: Darshan Sen Reviewed-By: James M Snell Reviewed-By: Tobias Nießen Reviewed-By: Daijiro Wachi --- src/node_url.cc | 20 +++++++++++++++++++- 1 file changed, 19 insertions(+), 1 deletion(-) diff --git a/src/node_url.cc b/src/node_url.cc index 056c6c466ba0ad..f9bf1cc6df297b 100644 --- a/src/node_url.cc +++ b/src/node_url.cc @@ -7,6 +7,7 @@ #include #include +#include #include #include @@ -1545,7 +1546,23 @@ void URL::Parse(const char* input, // https://url.spec.whatwg.org/#url-serializing std::string URL::SerializeURL(const struct url_data* url, bool exclude = false) { - std::string output = url->scheme; + std::string output; + output.reserve( + 10 + + url->scheme.size() + + url->username.size() + + url->password.size() + + url->host.size() + + url->query.size() + + url->fragment.size() + + url->href.size() + + std::accumulate( + url->path.begin(), + url->path.end(), + 0, + [](size_t sum, const auto& str) { return sum + str.size(); })); + + output += url->scheme; if (url->flags & URL_FLAGS_HAS_HOST) { output += "//"; if (url->flags & URL_FLAGS_HAS_USERNAME || @@ -1581,6 +1598,7 @@ std::string URL::SerializeURL(const struct url_data* url, if (!exclude && url->flags & URL_FLAGS_HAS_FRAGMENT) { output += "#" + url->fragment; } + output.shrink_to_fit(); return output; }