Skip to content

Commit

Permalink
chore: optimize DenseSet link allocation
Browse files Browse the repository at this point in the history
  • Loading branch information
BorysTheDev committed Oct 15, 2024
1 parent 1d5990c commit c74bc66
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 7 deletions.
18 changes: 14 additions & 4 deletions src/core/dense_set.cc
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,11 @@ DenseSet::DenseSet(MemoryResource* mr) : entries_(mr) {
}

DenseSet::~DenseSet() {
while (cached_link_num) {
mr()->deallocate(cached_links[--cached_link_num], sizeof(DenseLinkKey), alignof(DenseLinkKey));
--num_links_;
}

// We can not call Clear from the base class because it internally calls ObjDelete which is
// a virtual function. Therefore, destructor of the derived classes must clean up the table.
CHECK(entries_.empty());
Expand Down Expand Up @@ -798,13 +803,18 @@ uint32_t DenseSet::Scan(uint32_t cursor, const ItemCb& cb) const {
}

auto DenseSet::NewLink(void* data, DensePtr next) -> DenseLinkKey* {
LinkAllocator la(mr());
DenseLinkKey* lk = la.allocate(1);
la.construct(lk);
DenseLinkKey* lk = nullptr;
if (cached_link_num) {
lk = cached_links[--cached_link_num];
} else {
LinkAllocator la(mr());
lk = la.allocate(1);
la.construct(lk);
++num_links_;
}

lk->next = next;
lk->SetObject(data);
++num_links_;

return lk;
}
Expand Down
14 changes: 11 additions & 3 deletions src/core/dense_set.h
Original file line number Diff line number Diff line change
Expand Up @@ -390,9 +390,13 @@ class DenseSet {
DenseLinkKey* NewLink(void* data, DensePtr next);

inline void FreeLink(DenseLinkKey* plink) {
// deallocate the link if it is no longer a link as it is now in an empty list
mr()->deallocate(plink, sizeof(DenseLinkKey), alignof(DenseLinkKey));
--num_links_;
if (cached_link_num < max_cached_links) {
cached_links[cached_link_num++] = plink;
} else {
// deallocate the link if it is no longer a link as it is now in an empty list
mr()->deallocate(plink, sizeof(DenseLinkKey), alignof(DenseLinkKey));
--num_links_;
}
}

// Returns true if *node was deleted.
Expand Down Expand Up @@ -420,6 +424,10 @@ class DenseSet {
uint32_t time_now_ = 0;

mutable bool expiration_used_ = false;

static constexpr uint32_t max_cached_links = 8;
DenseLinkKey* cached_links[max_cached_links];
uint32_t cached_link_num = 0;
};

inline void* DenseSet::FindInternal(const void* obj, uint64_t hashcode, uint32_t cookie) const {
Expand Down

0 comments on commit c74bc66

Please sign in to comment.