Skip to content

Commit

Permalink
performance: avoid memory allocations with cast_to in binary operatio…
Browse files Browse the repository at this point in the history
…ns (#180)

also preallocate 64M objects
  • Loading branch information
hrzlgnm authored Dec 29, 2024
1 parent edb1bef commit 523c80e
Show file tree
Hide file tree
Showing 4 changed files with 255 additions and 147 deletions.
23 changes: 18 additions & 5 deletions source/gc.hpp
Original file line number Diff line number Diff line change
@@ -1,28 +1,41 @@
#pragma once

#include <concepts>
#include <cstddef>
#include <cstdlib>
#include <utility>
#include <vector>

template<typename T>
class gc
{
using store = std::vector<T*>;

public:
static void track(T* obj) { get_allocation_list().push_back(obj); }
static void track(T* obj) { get_store().push_back(obj); }

private:
static void cleanup()
{
for (T* obj : get_allocation_list()) {
for (T* obj : get_store()) {
delete obj;
}
}

static auto get_allocation_list() -> std::vector<T*>&
static auto get_store() -> store&
{
static std::vector<T*> allocations;
static const bool registered = []() { return std::atexit(cleanup); }();
static store allocations;
static const bool registered = []()
{
if constexpr (std::is_same_v<T, struct object>) {
constexpr auto object_reserve = static_cast<const size_t>(64 * 1024 * 1024);
allocations.reserve(object_reserve);
} else {
constexpr auto reserve = static_cast<const size_t>(128);
allocations.reserve(reserve);
}
return std::atexit(cleanup);
}();
(void)registered;
return allocations;
}
Expand Down
Loading

0 comments on commit 523c80e

Please sign in to comment.