Skip to content

Commit

Permalink
AK: Make FlyString::from_utf8*() avoid allocation if possible
Browse files Browse the repository at this point in the history
If we already have a FlyString instantiated for the given string,
look that up and return it instead of making a temporary String just to
use as a key into the FlyString table.
  • Loading branch information
awesomekling committed Mar 23, 2024
1 parent 7886119 commit c81f393
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 0 deletions.
12 changes: 12 additions & 0 deletions AK/FlyString.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -28,11 +28,23 @@ static auto& all_fly_strings()

ErrorOr<FlyString> FlyString::from_utf8(StringView string)
{
if (string.is_empty())
return FlyString {};
if (string.length() <= Detail::MAX_SHORT_STRING_BYTE_COUNT)
return FlyString { TRY(String::from_utf8(string)) };
if (auto it = all_fly_strings().find(string.hash(), [&](auto& entry) { return entry->bytes_as_string_view() == string; }); it != all_fly_strings().end())
return FlyString { Detail::StringBase(**it) };
return FlyString { TRY(String::from_utf8(string)) };
}

FlyString FlyString::from_utf8_without_validation(ReadonlyBytes string)
{
if (string.is_empty())
return FlyString {};
if (string.size() <= Detail::MAX_SHORT_STRING_BYTE_COUNT)
return FlyString { String::from_utf8_without_validation(string) };
if (auto it = all_fly_strings().find(StringView(string).hash(), [&](auto& entry) { return entry->bytes_as_string_view() == string; }); it != all_fly_strings().end())
return FlyString { Detail::StringBase(**it) };
return FlyString { String::from_utf8_without_validation(string) };
}

Expand Down
5 changes: 5 additions & 0 deletions AK/FlyString.h
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,11 @@ class FlyString {
}

private:
explicit FlyString(Detail::StringBase data)
: m_data(move(data))
{
}

Detail::StringBase m_data;
};

Expand Down

0 comments on commit c81f393

Please sign in to comment.