From 9f73d18094ebedf94cb7b0507c195ada13c1d36a Mon Sep 17 00:00:00 2001 From: Robin Haberkorn Date: Tue, 4 Aug 2026 22:31:31 +0200 Subject: dlmalloc: avoid unnecessary atomics in realloc() * Atomics are much cheaper than mutexes for such rarely contented fields, but they are still much slower than plain arithmetics. * For realloc(), we'd expect relatively small changes between calls which means that the chunk's usable size probably won't change. Therefore it makes sense to check whether we'd get a zero addition to teco_memory_usage. * We will now have at most one atomic add in realloc() instead of always 2 atomic operations. --- src/memory.c | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) (limited to 'src') diff --git a/src/memory.c b/src/memory.c index d8de483..97bc627 100644 --- a/src/memory.c +++ b/src/memory.c @@ -338,11 +338,11 @@ calloc(size_t nmemb, size_t size) void * __attribute__((used)) realloc(void *ptr, size_t size) { - if (ptr) - g_atomic_int_add(&teco_memory_usage, -dlmalloc_usable_size(ptr)); + gssize len = ptr ? dlmalloc_usable_size(ptr) : 0; ptr = dlrealloc(ptr, size); - if (G_LIKELY(ptr != NULL)) - g_atomic_int_add(&teco_memory_usage, dlmalloc_usable_size(ptr)); + gssize delta = (G_LIKELY(ptr != NULL) ? (gssize)dlmalloc_usable_size(ptr) : 0) - len; + if (delta != 0) + g_atomic_int_add(&teco_memory_usage, delta); return ptr; } -- cgit v1.2.3