GeezerVison is showing github.com — src: reserve string allocation space early in URL::SerializeURL · hernanc/node@889534e
File tree
Expand file treeCollapse file tree
Open diff view settings
Expand file treeCollapse file tree
Open diff view settings
Collapse file
Copy file name to clipboardExpand all lines: src/node_url.cc +19-1Lines changed: 19 additions & 1 deletion | Original file line number | Diff line number | Diff line change |
|---|
|
7 | 7 |
|
8 | 8 | #include <cmath> |
9 | 9 | #include <cstdio> |
| 10 | +#include <numeric> |
10 | 11 | #include <string> |
11 | 12 | #include <vector> |
12 | 13 |
|
@@ -1545,7 +1546,23 @@ void URL::Parse(const char* input, |
1545 | 1546 | // https://url.spec.whatwg.org/#url-serializing |
1546 | 1547 | std::string URL::SerializeURL(const struct url_data* url, |
1547 | 1548 | 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; |
1549 | 1566 | if (url->flags & URL_FLAGS_HAS_HOST) { |
1550 | 1567 | output += "//"; |
1551 | 1568 | if (url->flags & URL_FLAGS_HAS_USERNAME || |
@@ -1581,6 +1598,7 @@ std::string URL::SerializeURL(const struct url_data* url, |
1581 | 1598 | if (!exclude && url->flags & URL_FLAGS_HAS_FRAGMENT) { |
1582 | 1599 | output += "#" + url->fragment; |
1583 | 1600 | } |
| 1601 | + output.shrink_to_fit(); |
1584 | 1602 | return output; |
1585 | 1603 | } |
1586 | 1604 |
|
|