mirror of
https://github.com/fergalmoran/ladybird.git
synced 2026-01-06 08:36:15 +00:00
AK: Construct Strings from StringBuilder without re-allocating the data
Currently, invoking StringBuilder::to_string will re-allocate the string data to construct the String. This is wasteful both in terms of memory and speed. The goal here is to simply hand the string buffer over to String, and let String take ownership of that buffer. To do this, StringBuilder must have the same memory layout as Detail::StringData. This layout is just the members of the StringData class followed by the string itself. So when a StringBuilder is created, we reserve sizeof(StringData) bytes at the front of the buffer. StringData can then construct itself into the buffer with placement new. Things to note: * StringData must now be aware of the actual capacity of its buffer, as that can be larger than the string size. * We must take care not to pass ownership of inlined string buffers, as these live on the stack.
This commit is contained in:
committed by
Andreas Kling
parent
77eef8a8f6
commit
29879a69a4
@@ -90,6 +90,19 @@ bool StringBase::operator==(StringBase const& other) const
|
||||
return bytes() == other.bytes();
|
||||
}
|
||||
|
||||
void StringBase::replace_with_string_builder(StringBuilder& builder)
|
||||
{
|
||||
if (builder.length() <= MAX_SHORT_STRING_BYTE_COUNT) {
|
||||
return replace_with_new_short_string(builder.length(), [&](Bytes buffer) {
|
||||
builder.string_view().bytes().copy_to(buffer);
|
||||
});
|
||||
}
|
||||
|
||||
destroy_string();
|
||||
|
||||
m_data = &StringData::create_from_string_builder(builder).leak_ref();
|
||||
}
|
||||
|
||||
ErrorOr<Bytes> StringBase::replace_with_uninitialized_buffer(size_t byte_count)
|
||||
{
|
||||
if (byte_count <= MAX_SHORT_STRING_BYTE_COUNT)
|
||||
|
||||
Reference in New Issue
Block a user