]> git.kaiwu.me - njs.git/commitdiff
Memory pool: cached slot index in a page
authorDmitry Volyntsev <xeioex@nginx.com>
Tue, 8 Sep 2026 22:50:16 +0000 (15:50 -0700)
committerDmitry Volyntsev <xeioexception@gmail.com>
Fri, 18 Sep 2026 20:42:16 +0000 (13:42 -0700)
Previously, freeing a chunk searched the pool slots linearly to map the
chunk size back to its slot.

The fix is to keep the slot index in the page descriptor, in a byte
that was unused.

src/njs_mp.c

index f39fb7113696139d1bdda41f2a889e332eedc2f7..7382c796bab38dec42f7c99da23ca2148819b730 100644 (file)
@@ -44,7 +44,8 @@ typedef struct {
     /* Number of free chunks of a chunked page. */
     uint8_t                     chunks;
 
-    uint8_t                     _unused;
+    /* Index of the pool slot the chunks of the page belong to. */
+    uint8_t                     slot;
 
     /* Chunk bitmap.  There can be no more than 32 chunks in a page. */
     uint8_t                     map[4];
@@ -464,6 +465,7 @@ njs_mp_alloc_small(njs_mp_t *mp, size_t size)
                 /* slot->chunks are already one less. */
                 page->chunks = slot->chunks;
                 page->size = size >> mp->chunk_size_shift;
+                page->slot = slot - mp->slots;
 
                 p = njs_mp_page_addr(mp, page);
             }
@@ -812,8 +814,9 @@ njs_mp_chunk_free(njs_mp_t *mp, njs_mp_block_t *cluster,
 
         njs_mp_chunk_set_free(page->map, chunk);
 
-        /* Find a slot with appropriate chunk size. */
-        for (slot = mp->slots; slot->size < size; slot++) { /* void */ }
+        slot = &mp->slots[page->slot];
+
+        njs_assert(slot->size == size);
 
         if (page->chunks != slot->chunks) {
             page->chunks++;