mirror of
https://github.com/LadybirdBrowser/ladybird.git
synced 2024-11-22 07:30:19 +00:00
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:
parent
8064c9fc4d
commit
cae184d7cf
Notes:
sideshowbarker
2024-07-17 08:35:21 +09:00
Author: https://github.com/trflynn89 Commit: https://github.com/SerenityOS/serenity/commit/cae184d7cf Pull-request: https://github.com/SerenityOS/serenity/pull/22562 Reviewed-by: https://github.com/nico ✅
1 changed files with 9 additions and 4 deletions
|
@ -412,10 +412,15 @@ Optional<size_t> find_last(StringView haystack, char needle)
|
|||
|
||||
Optional<size_t> find_last(StringView haystack, StringView needle)
|
||||
{
|
||||
for (size_t i = haystack.length(); i > 0; --i) {
|
||||
auto value = StringUtils::find(haystack, needle, i - 1);
|
||||
if (value.has_value())
|
||||
return value;
|
||||
if (needle.length() > haystack.length())
|
||||
return {};
|
||||
|
||||
for (size_t i = haystack.length() - needle.length();; --i) {
|
||||
if (haystack.substring_view(i, needle.length()) == needle)
|
||||
return i;
|
||||
|
||||
if (i == 0)
|
||||
break;
|
||||
}
|
||||
|
||||
return {};
|
||||
|
|
Loading…
Reference in a new issue