File tree Expand file tree Collapse file tree
examples/google_benchmark_cmake Expand file tree Collapse file tree Original file line number Diff line number Diff line change 77
88// Run-length encoding: compress consecutive repeated characters
99// Example: "aaabbbccc" -> "3a3b3c"
10+ // NOTE: Intentionally inefficient - no pre-allocation to show multiple
11+ // allocations
1012static std::string rle_encode (const std::string& input) {
1113 if (input.empty ()) return " " ;
1214
13- std::string result;
14- result.reserve (input.size ()); // Pre-allocate reasonable size
15+ std::string result; // No reserve - will trigger multiple reallocations
1516
1617 char current = input[0 ];
1718 size_t count = 1 ;
@@ -20,12 +21,19 @@ static std::string rle_encode(const std::string& input) {
2021 if (input[i] == current) {
2122 count++;
2223 } else {
23- result += std::to_string (count) + current;
24+ // Create intermediate strings for each run
25+ std::string count_str = std::to_string (count);
26+ std::string run_encoded = count_str + current;
27+ result += run_encoded; // Concatenation causes reallocations
2428 current = input[i];
2529 count = 1 ;
2630 }
2731 }
28- result += std::to_string (count) + current;
32+
33+ // Final run
34+ std::string count_str = std::to_string (count);
35+ std::string final_run = count_str + current;
36+ result += final_run;
2937
3038 return result;
3139}
You can’t perform that action at this time.
0 commit comments