Skip to content

Commit 321bd35

Browse files
committed
Merge pull request #100294 from Ivorforce/count-no-realloc
Optimize `String.count` and `String.countn` by avoiding repeated reallocations.
2 parents 4cf1b0d + ef3eecd commit 321bd35

File tree

1 file changed

+12
-16
lines changed

1 file changed

+12
-16
lines changed

core/string/ustring.cpp

Lines changed: 12 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -3735,14 +3735,12 @@ int String::_count(const String &p_string, int p_from, int p_to, bool p_case_ins
37353735
return 0;
37363736
}
37373737
int c = 0;
3738-
int idx = -1;
3739-
do {
3740-
idx = p_case_insensitive ? str.findn(p_string) : str.find(p_string);
3741-
if (idx != -1) {
3742-
str = str.substr(idx + slen, str.length() - slen);
3743-
++c;
3744-
}
3745-
} while (idx != -1);
3738+
int idx = 0;
3739+
while ((idx = p_case_insensitive ? str.findn(p_string, idx) : str.find(p_string, idx)) != -1) {
3740+
// Skip the occurrence itself.
3741+
idx += slen;
3742+
++c;
3743+
}
37463744
return c;
37473745
}
37483746

@@ -3774,14 +3772,12 @@ int String::_count(const char *p_string, int p_from, int p_to, bool p_case_insen
37743772
return 0;
37753773
}
37763774
int c = 0;
3777-
int idx = -1;
3778-
do {
3779-
idx = p_case_insensitive ? str.findn(p_string) : str.find(p_string);
3780-
if (idx != -1) {
3781-
str = str.substr(idx + substring_length, str.length() - substring_length);
3782-
++c;
3783-
}
3784-
} while (idx != -1);
3775+
int idx = 0;
3776+
while ((idx = p_case_insensitive ? str.findn(p_string, idx) : str.find(p_string, idx)) != -1) {
3777+
// Skip the occurrence itself.
3778+
idx += substring_length;
3779+
++c;
3780+
}
37853781
return c;
37863782
}
37873783

0 commit comments

Comments
 (0)