Skip to content

Commit

Permalink
Minor tidying of block size calculations - avoid unnecessary memory b…
Browse files Browse the repository at this point in the history
…arriers and likely cache miss for most recent block size.

PiperOrigin-RevId: 708296701
  • Loading branch information
protobuf-github-bot authored and copybara-github committed Dec 20, 2024
1 parent 1803f8b commit 79a34c4
Showing 1 changed file with 13 additions and 4 deletions.
17 changes: 13 additions & 4 deletions upb/mem/arena.c
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,11 @@
// Must be last.
#include "upb/port/def.inc"

static UPB_ATOMIC(size_t) max_block_size = 32 << 10;
static UPB_ATOMIC(size_t) g_max_block_size = 32 << 10;

void upb_Arena_SetMaxBlockSize(size_t max) { max_block_size = max; }
void upb_Arena_SetMaxBlockSize(size_t max) {
upb_Atomic_Store(&g_max_block_size, max, memory_order_relaxed);
}

typedef struct upb_MemBlock {
// Atomic only for the benefit of SpaceAllocated().
Expand Down Expand Up @@ -264,8 +266,15 @@ static void _upb_Arena_AddBlock(upb_Arena* a, void* ptr, size_t size) {
static bool _upb_Arena_AllocBlock(upb_Arena* a, size_t size) {
upb_ArenaInternal* ai = upb_Arena_Internal(a);
if (!ai->block_alloc) return false;
upb_MemBlock* last_block = upb_Atomic_Load(&ai->blocks, memory_order_acquire);
size_t last_size = last_block != NULL ? last_block->size : 128;
size_t last_size = 128;
upb_MemBlock* last_block = upb_Atomic_Load(&ai->blocks, memory_order_relaxed);
if (last_block) {
last_size = a->UPB_PRIVATE(end) - (char*)last_block;
}

// Relaxed order is safe here as we don't need any ordering with the setter.
size_t max_block_size =
upb_Atomic_Load(&g_max_block_size, memory_order_relaxed);

// Don't naturally grow beyond the max block size.
size_t clamped_size = UPB_MIN(last_size * 2, max_block_size);
Expand Down

0 comments on commit 79a34c4

Please sign in to comment.