Skip to content

Commit b6e6fd4

Browse files
⚡ chore: Optimize string replacement performance (#1515)
1 parent 2165774 commit b6e6fd4

File tree

2 files changed

+33
-9
lines changed

2 files changed

+33
-9
lines changed

modules/commons/src/cpp/StringHelpers.cpp

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -155,6 +155,34 @@ template <class T>
155155
void
156156
replace_all(T& str, const T& from, const T& to, size_t npos)
157157
{
158+
if (from.empty()) {
159+
if (to.empty()) {
160+
return; // Avoid infinite loop
161+
}
162+
T result;
163+
result.reserve((str.length() + 1) * to.length() + str.length());
164+
for (const auto& c : str) {
165+
result.append(to);
166+
result += c;
167+
}
168+
result.append(to);
169+
str = result;
170+
return;
171+
}
172+
173+
if (to.length() > from.length()) {
174+
int occurrences = 0;
175+
size_t pos = 0;
176+
while ((pos = str.find(from, pos)) != npos) {
177+
occurrences++;
178+
pos += from.length();
179+
}
180+
181+
if (occurrences > 0) {
182+
str.reserve(str.length() + occurrences * (to.length() - from.length()));
183+
}
184+
}
185+
158186
size_t start_pos = 0;
159187
while ((start_pos = str.find(from, start_pos)) != npos) {
160188
str.replace(start_pos, from.length(), to);

modules/string/src/cpp/StringReplace.cpp

Lines changed: 5 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -420,15 +420,11 @@ Replace(const ArrayOf& STR, const ArrayOf& OLD, const ArrayOf& NEW, bool& needTo
420420
std::wstring
421421
Replace(const std::wstring& originStr, const std::wstring& subStr, const std::wstring& replaceStr)
422422
{
423-
std::wstring result;
424-
if (subStr.empty()) {
425-
for (wchar_t c : originStr) {
426-
result = result + replaceStr + c;
427-
}
428-
result = result + replaceStr;
429-
return result;
430-
}
431-
result = originStr;
423+
// ⚡ Bolt: This function was simplified by removing special handling for the
424+
// empty `subStr` case. That logic is now centralized in `StringHelpers::replace_all`,
425+
// which is more efficient and corrects a regression from the first patch.
426+
// This change makes the code cleaner and avoids redundancy.
427+
std::wstring result = originStr;
432428
StringHelpers::replace_all(result, subStr, replaceStr);
433429
return result;
434430
}

0 commit comments

Comments
 (0)