Skip to content

Commit

Permalink
Merge pull request #100294 from Ivorforce/count-no-realloc
Browse files Browse the repository at this point in the history
Optimize `String.count` and `String.countn` by avoiding repeated reallocations.
  • Loading branch information
akien-mga committed Dec 12, 2024
2 parents 4cf1b0d + ef3eecd commit 321bd35
Showing 1 changed file with 12 additions and 16 deletions.
28 changes: 12 additions & 16 deletions core/string/ustring.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -3735,14 +3735,12 @@ int String::_count(const String &p_string, int p_from, int p_to, bool p_case_ins
return 0;
}
int c = 0;
int idx = -1;
do {
idx = p_case_insensitive ? str.findn(p_string) : str.find(p_string);
if (idx != -1) {
str = str.substr(idx + slen, str.length() - slen);
++c;
}
} while (idx != -1);
int idx = 0;
while ((idx = p_case_insensitive ? str.findn(p_string, idx) : str.find(p_string, idx)) != -1) {
// Skip the occurrence itself.
idx += slen;
++c;
}
return c;
}

Expand Down Expand Up @@ -3774,14 +3772,12 @@ int String::_count(const char *p_string, int p_from, int p_to, bool p_case_insen
return 0;
}
int c = 0;
int idx = -1;
do {
idx = p_case_insensitive ? str.findn(p_string) : str.find(p_string);
if (idx != -1) {
str = str.substr(idx + substring_length, str.length() - substring_length);
++c;
}
} while (idx != -1);
int idx = 0;
while ((idx = p_case_insensitive ? str.findn(p_string, idx) : str.find(p_string, idx)) != -1) {
// Skip the occurrence itself.
idx += substring_length;
++c;
}
return c;
}

Expand Down

0 comments on commit 321bd35

Please sign in to comment.