AK: Improve performance of StringUtils::find_last

The current algorithm is currently O(N^2) because we forward-search an
ever-increasing substring of the haystack. This implementation reduces
the search time of a 500,000-length string (where the desired needle is
at index 0) from 72 seconds to 2-3 milliseconds.
This commit is contained in:
Timothy Flynn 2024-01-03 16:48:42 -05:00 committed by Tim Flynn
parent 8064c9fc4d
commit cae184d7cf

View file

@ -412,10 +412,15 @@ Optional<size_t> find_last(StringView haystack, char needle)
Optional<size_t> find_last(StringView haystack, StringView needle) Optional<size_t> find_last(StringView haystack, StringView needle)
{ {
for (size_t i = haystack.length(); i > 0; --i) { if (needle.length() > haystack.length())
auto value = StringUtils::find(haystack, needle, i - 1); return {};
if (value.has_value())
return value; for (size_t i = haystack.length() - needle.length();; --i) {
if (haystack.substring_view(i, needle.length()) == needle)
return i;
if (i == 0)
break;
} }
return {}; return {};