Substring Extraction: Owning String vs String View
Question 43 / 51 • Correct so far: 0 (0 answered)
String Substr
std::size_t sumSubstrLengths(const std::string& src, std::size_t subLen) {
std::size_t total = 0;
for (std::size_t i = 0; i + subLen <= src.size(); i += subLen) {
std::string sub = src.substr(i, subLen);
total += sub.size();
}
return total;
}
std::size_t n = sumSubstrLengths(SOURCE, kSubLen); View Substr
std::size_t sumSubstrLengths(std::string_view src, std::size_t subLen) {
std::size_t total = 0;
for (std::size_t i = 0; i + subLen <= src.size(); i += subLen) {
std::string_view sub = src.substr(i, subLen);
total += sub.size();
}
return total;
}
std::size_t n = sumSubstrLengths(SOURCE_VIEW, kSubLen); Shared test data (shared-setup)
static const std::string SOURCE = []() {
std::string s;
s.reserve(1024);
for (int i = 0; i < 64; ++i)
s += "word" + std::to_string(i) + " ";
return s;
}();
static const std::string_view SOURCE_VIEW{SOURCE};
constexpr std::size_t kSubLen = 8; Which snippet is faster?
Snippet B is faster. std::string::substr creates a new string and copies
characters, while std::string_view::substr just creates a view over the
original data. No allocation and no copy makes the view-based path cheaper.
Benchmark results
| Snippet | CPU time / iteration | Speedup |
|---|---|---|
| String Substr | 134 ns | 1.0× |
| View Substr | 23.7 ns | 5.6× |
Explore the source
Open in Compiler ExplorerQuiz complete. You can return to the question list to restart and compare.