Skip to content

Commit a7a5514

Browse files
committed
Optimize string split function for performance
1 parent 6f70ab2 commit a7a5514

File tree

1 file changed

+19
-5
lines changed

1 file changed

+19
-5
lines changed

cpr/util.cpp

Lines changed: 19 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -113,13 +113,27 @@ Header parseHeader(const std::string& headers, std::string* status_line, std::st
113113
return header;
114114
}
115115

116-
std::vector<std::string> split(const std::string& to_split, char delimiter) {
116+
std::vector<std::string> split(const std::string& to_split, char delimiter){
117117
std::vector<std::string> tokens;
118118

119-
std::stringstream stream(to_split);
120-
std::string item;
121-
while (std::getline(stream, item, delimiter)) {
122-
tokens.push_back(item);
119+
if (to_split.empty()){
120+
return tokens;
121+
}
122+
123+
const size_t num_delims = static_cast<size_t>(std::count(to_split.begin(), to_split.end(), delimiter));
124+
const bool ends_with_delim = (to_split.back() == delimiter);
125+
const size_t reserve_size = num_delims + (ends_with_delim ? 0 : 1);
126+
tokens.reserve(reserve_size);
127+
128+
size_t start = 0;
129+
size_t pos;
130+
while ((pos = to_split.find(delimiter, start)) != std::string::npos){
131+
tokens.emplace_back(to_split, start, pos - start);
132+
start = pos + 1;
133+
}
134+
135+
if (start < to_split.size()){
136+
tokens.emplace_back(to_split, start, to_split.size() - start);
123137
}
124138

125139
return tokens;

0 commit comments

Comments
 (0)