not a beautiful or unique snowflake (nothings) wrote,
not a beautiful or unique snowflake
nothings



I needed an "arena" allocator (allocates individual small blocks, frees them all at once) since I had a library that was spending most of its time freeing data. I didn't want to spend very long on it, so I tried to write a very small, quick-and-dirty one.

This is one of the reasons why garbage collection just isn't as much of a win as people think. This gets me better performance than GC would, didn't take long to switch over to using, and writing this custom allocator took me, I dunno, ten minutes (and it's perfectly reusable, too; I just didn't have one lying around, and besides I wanted it to be short so it could live in the same file as the rest of the library for ease of distribution).

typedef struct Pool
{
   struct Pool *next;
   int    current, limit;
   char   data[1];
} Pool;

#define POOL_SIZE   65500
static void *allocFromPool(int size, Pool **pool)
{
   Pool *p;
   void *result;

   if (!*pool || (*pool)->current + size > (*pool)->limit) {
      int alloc = size > POOL_SIZE ? size : POOL_SIZE;   // make sure allocation is big enough
      p = malloc(sizeof(Pool)-1 + alloc);
      p->current = 0;
      p->limit   = alloc;
      p->next    = *pool;     // thread previous pool pointer along
      *pool      = p;
   } else {
      p = *pool;
   }

   result = p->data + p->current;
   p->current += size;
   return result;
}

static void freePool(Pool *p)
{
   while (p != NULL) {
      Pool *q = p->next;
      free(p);
      p = q;
   }
}
Subscribe
  • Post a new comment

    Error

    default userpic

    Your reply will be screened

    Your IP address will be recorded 

  • 12 comments