Skip to content

Commit

Permalink
Optimize TransitEventBuffer expansion
Browse files Browse the repository at this point in the history
  • Loading branch information
odygrd committed Sep 14, 2024
1 parent 0c5a27b commit b823618
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 2 deletions.
5 changes: 4 additions & 1 deletion include/quill/backend/TransitEvent.h
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ class LoggerBase;
struct TransitEvent
{
/***/
TransitEvent() { formatted_msg.reserve(32); }
TransitEvent() = default;

/***/
~TransitEvent() = default;
Expand Down Expand Up @@ -81,6 +81,9 @@ struct TransitEvent
return (macro_metadata->log_level() != LogLevel::Dynamic) ? macro_metadata->log_level() : dynamic_log_level;
}

/***/
void reserve_formatted_msg(size_t capacity) { formatted_msg.reserve(capacity); }

uint64_t timestamp{0};
MacroMetadata const* macro_metadata{nullptr};
detail::LoggerBase* logger_base{nullptr};
Expand Down
15 changes: 14 additions & 1 deletion include/quill/backend/TransitEventBuffer.h
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,10 @@ class TransitEventBuffer
_storage(std::make_unique<TransitEvent[]>(_capacity)),
_mask(_capacity - 1u)
{
for (size_t i = 0; i < _capacity; ++i)
{
_storage.get()[i].reserve_formatted_msg(32);
}
}

TransitEventBuffer(TransitEventBuffer const&) = delete;
Expand Down Expand Up @@ -108,13 +112,22 @@ class TransitEventBuffer

auto new_storage = std::make_unique<TransitEvent[]>(new_capacity);

// Copy existing elements to the new storage
// Move existing elements from the old storage to the new storage.
// Since the buffer is full, this moves all the previous TransitEvents, preserving their order.
// The reader position and mask are used to handle the circular buffer's wraparound.
size_t const current_size = size();
for (size_t i = 0; i < current_size; ++i)
{
new_storage[i] = std::move(_storage[(_reader_pos + i) & _mask]);
}

// For the new elements in the expanded buffer, reserve memory for formatted messages.
// This mirrors the pre-allocation done in the constructor
for (size_t i = current_size; i < new_capacity; ++i)
{
new_storage.get()[i].reserve_formatted_msg(32);
}

_storage = std::move(new_storage);
_capacity = new_capacity;
_mask = _capacity - 1;
Expand Down

0 comments on commit b823618

Please sign in to comment.