Skip to content

Commit

Permalink
src: reserve string allocation space early in URL::SerializeURL
Browse files Browse the repository at this point in the history
This can be useful for performance when doing many string
concatenations.

PR-URL: #41759
Reviewed-By: Benjamin Gruenbaum <[email protected]>
Reviewed-By: Tiancheng "Timothy" Gu <[email protected]>
Reviewed-By: Darshan Sen <[email protected]>
Reviewed-By: James M Snell <[email protected]>
Reviewed-By: Tobias Nießen <[email protected]>
Reviewed-By: Daijiro Wachi <[email protected]>
  • Loading branch information
addaleax authored and nodejs-github-bot committed Feb 11, 2022
1 parent acd35ec commit 889534e
Showing 1 changed file with 19 additions and 1 deletion.
20 changes: 19 additions & 1 deletion src/node_url.cc
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@

#include <cmath>
#include <cstdio>
#include <numeric>
#include <string>
#include <vector>

Expand Down Expand Up @@ -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 ||
Expand Down Expand Up @@ -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;
}

Expand Down

0 comments on commit 889534e

Please sign in to comment.