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: nodejs#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>
  • Loading branch information
addaleax authored and bengl committed Feb 21, 2022
1 parent 276b796 commit 21be3fb
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 21be3fb

Please sign in to comment.