James wrote:

> > BTW, something that I forgot to point out last time: for very small
> > structures (e.g. the 8-byte `struct node'), it's worth writing a
> > special-case allocator function, which allocates larger blocks of
> > memory using malloc (or equivalent), and then allocates individual
> > node structures from these.
> 
> can you expand on that? sounds interesting.

#include <stdlib.h>

typedef struct node {
        void *data;
        struct node *next;
} node;

static const int nodes_per_block = 1000;

static node *free_list;

static void get_more_nodes(void)
{
        node *block = malloc(nodes_per_block * sizeof(node));
        int i;

        for (i = 0; i < nodes_per_block - 1; i++)
                block[i].next = &block[i + 1];

        block[nodes_per_block - 1].next = free_list;
        free_list = block;
}

node *alloc_node(void)
{
        node *n;

        if (!free_list)
                get_more_nodes();

        n = free_list;
        free_list = free_list->next;
        return n;
}

void free_node(node *n)
{
        n->next = free_list;
        free_list = n;
}

-- 
Glynn Clements <[EMAIL PROTECTED]>

Reply via email to