From 7ecf94d4b339bc2197f449f0f1538f2915313087 Mon Sep 17 00:00:00 2001 From: pixel Date: Mon, 28 Jan 2008 12:49:06 +0000 Subject: Trying with a hashtable instead of a dumb structure. --- recycle.c | 87 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 87 insertions(+) create mode 100644 recycle.c (limited to 'recycle.c') diff --git a/recycle.c b/recycle.c new file mode 100644 index 0000000..261c54f --- /dev/null +++ b/recycle.c @@ -0,0 +1,87 @@ +/* +-------------------------------------------------------------------- +By Bob Jenkins, September 1996. recycle.c +You may use this code in any way you wish, and it is free. No warranty. + +This manages memory for commonly-allocated structures. +It allocates RESTART to REMAX items at a time. +Timings have shown that, if malloc is used for every new structure, + malloc will consume about 90% of the time in a program. This + module cuts down the number of mallocs by an order of magnitude. +This also decreases memory fragmentation, and freeing structures + only requires freeing the root. +-------------------------------------------------------------------- +*/ + +#include +#include +#include +#include "recycle.h" + +#define align(a) (((uint32_t)a+(sizeof(void *)-1))&(~(sizeof(void *)-1))) + +reroot *remkroot(size) +size_t size; +{ + reroot *r = (reroot *)remalloc(sizeof(reroot), "recycle.c, root"); + r->list = (recycle *)0; + r->trash = (recycle *)0; + r->size = align(size); + r->logsize = RESTART; + r->numleft = 0; + return r; +} + +void refree(r) +struct reroot *r; +{ + recycle *temp; + if ((temp = r->list)) while (r->list) + { + temp = r->list->next; + free((char *)r->list); + r->list = temp; + } + free((char *)r); + return; +} + +/* to be called from the macro renew only */ +char *renewx(r) +struct reroot *r; +{ + recycle *temp; + if (r->trash) + { /* pull a node off the trash heap */ + temp = r->trash; + r->trash = temp->next; + (void)memset((void *)temp, 0, r->size); + } + else + { /* allocate a new block of nodes */ + r->numleft = r->size*((uint32_t)1<logsize); + if (r->numleft < REMAX) ++r->logsize; + temp = (recycle *)remalloc(sizeof(recycle) + r->numleft, + "recycle.c, data"); + temp->next = r->list; + r->list = temp; + r->numleft-=r->size; + temp = (recycle *)((char *)(r->list+1)+r->numleft); + } + return (char *)temp; +} + +char *remalloc(len, purpose) +size_t len; +char *purpose; +{ + char *x = (char *)malloc(len); + if (!x) + { + fprintf(stderr, "malloc of %d failed for %s\n", + len, purpose); + exit(-1); + } + return x; +} + -- cgit v1.2.3