Skip to content

Commit 470f870

Browse files
addaleaxbengl
authored andcommitted
src: reserve string allocation space early in URL::SerializeURL
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]>
1 parent 554cd2c commit 470f870

File tree

1 file changed

+19
-1
lines changed

1 file changed

+19
-1
lines changed

src/node_url.cc

+19-1
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77

88
#include <cmath>
99
#include <cstdio>
10+
#include <numeric>
1011
#include <string>
1112
#include <vector>
1213

@@ -1545,7 +1546,23 @@ void URL::Parse(const char* input,
15451546
// https://url.spec.whatwg.org/#url-serializing
15461547
std::string URL::SerializeURL(const struct url_data* url,
15471548
bool exclude = false) {
1548-
std::string output = url->scheme;
1549+
std::string output;
1550+
output.reserve(
1551+
10 +
1552+
url->scheme.size() +
1553+
url->username.size() +
1554+
url->password.size() +
1555+
url->host.size() +
1556+
url->query.size() +
1557+
url->fragment.size() +
1558+
url->href.size() +
1559+
std::accumulate(
1560+
url->path.begin(),
1561+
url->path.end(),
1562+
0,
1563+
[](size_t sum, const auto& str) { return sum + str.size(); }));
1564+
1565+
output += url->scheme;
15491566
if (url->flags & URL_FLAGS_HAS_HOST) {
15501567
output += "//";
15511568
if (url->flags & URL_FLAGS_HAS_USERNAME ||
@@ -1581,6 +1598,7 @@ std::string URL::SerializeURL(const struct url_data* url,
15811598
if (!exclude && url->flags & URL_FLAGS_HAS_FRAGMENT) {
15821599
output += "#" + url->fragment;
15831600
}
1601+
output.shrink_to_fit();
15841602
return output;
15851603
}
15861604

0 commit comments

Comments
 (0)