diff options
author | Anna Henningsen <anna@addaleax.net> | 2022-01-30 00:20:10 +0300 |
---|---|---|
committer | Node.js GitHub Bot <github-bot@iojs.org> | 2022-02-11 14:40:11 +0300 |
commit | 889534ec35c167901164424f789edfbea0e1c75b (patch) | |
tree | 6b2b30c424f9aba02e8a4094febfa5a51daadefa /src/node_url.cc | |
parent | acd35ecbe733215df05af80103db561eaeadb58c (diff) |
src: reserve string allocation space early in URL::SerializeURL
This can be useful for performance when doing many string
concatenations.
PR-URL: https://github.com/nodejs/node/pull/41759
Reviewed-By: Benjamin Gruenbaum <benjamingr@gmail.com>
Reviewed-By: Tiancheng "Timothy" Gu <timothygu99@gmail.com>
Reviewed-By: Darshan Sen <raisinten@gmail.com>
Reviewed-By: James M Snell <jasnell@gmail.com>
Reviewed-By: Tobias Nießen <tniessen@tnie.de>
Reviewed-By: Daijiro Wachi <daijiro.wachi@gmail.com>
Diffstat (limited to 'src/node_url.cc')
-rw-r--r-- | src/node_url.cc | 20 |
1 files changed, 19 insertions, 1 deletions
diff --git a/src/node_url.cc b/src/node_url.cc index 056c6c466ba..f9bf1cc6df2 100644 --- a/src/node_url.cc +++ b/src/node_url.cc @@ -7,6 +7,7 @@ #include <cmath> #include <cstdio> +#include <numeric> #include <string> #include <vector> @@ -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; } |