Skip to content

Commit

Permalink
Preallocating join string
Browse files Browse the repository at this point in the history
Preallocating the length of the join string means that there wont be reallocations being done within the loop speeding it up
  • Loading branch information
AsherGlick committed Oct 31, 2023
1 parent f38417d commit 53edeb6
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 2 deletions.
9 changes: 8 additions & 1 deletion xml_converter/src/string_helper.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -48,8 +48,15 @@ vector<string> split(string input, string delimiter) {
return output;
}

string join(const vector<string>& input, string delimiter) {
string join(const vector<string>& input, const string& delimiter) {
string result;
size_t size = 0;
for (size_t i = 0; i < input.size(); i++) {
size += input[i].size() + delimiter.size();
}

result.resize(size);

for (size_t i = 0; i < input.size(); i++) {
result += input[i];
// Don't add delimiter after the last element
Expand Down
2 changes: 1 addition & 1 deletion xml_converter/src/string_helper.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ bool normalized_matches_any(std::string test, std::vector<std::string> list);
std::string lowercase(std::string);

std::vector<std::string> split(std::string input, std::string delimiter);
std::string join(const std::vector<std::string>& input, std::string delimiter);
std::string join(const std::vector<std::string>& input, const std::string& delimiter);

std::string normalize(std::string input_string);

Expand Down

0 comments on commit 53edeb6

Please sign in to comment.