2 * mempool.c: efficient memory allocation
4 * MonoMemPool is for fast allocation of memory. We free
5 * all memory when the pool is destroyed.
8 * Dietmar Maurer (dietmar@ximian.com)
10 * (C) 2001 Ximian, Inc.
20 * MonoMemPool is for fast allocation of memory. We free
21 * all memory when the pool is destroyed.
26 #define MONO_MEMPOOL_PAGESIZE 8192
33 double pad; /* to assure proper alignment */
41 * Returns: a new memory pool.
46 MonoMemPool *pool = g_malloc (MONO_MEMPOOL_PAGESIZE);
49 pool->pos = (char *)pool + sizeof (MonoMemPool);
50 pool->rest = MONO_MEMPOOL_PAGESIZE - sizeof (MonoMemPool);
51 pool->d.allocated = MONO_MEMPOOL_PAGESIZE;
56 * mono_mempool_destroy:
57 * @pool: the momory pool to destroy
59 * Free all memory associated with this pool.
62 mono_mempool_destroy (MonoMemPool *pool)
75 mono_mempool_empty (MonoMemPool *pool)
77 pool->pos = (char *)pool + sizeof (MonoMemPool);
78 pool->rest = MONO_MEMPOOL_PAGESIZE - sizeof (MonoMemPool);
83 * @pool: the momory pool we need stats for
85 * Print a few stats about the mempool
88 mono_mempool_stats (MonoMemPool *pool)
92 guint32 still_free = 0;
96 still_free += p->rest;
102 g_print ("Mempool %p stats:\n", pool);
103 g_print ("Total mem allocated: %d\n", pool->d.allocated);
104 g_print ("Num chunks: %d\n", count);
105 g_print ("Free memory: %d\n", still_free);
110 * mono_mempool_alloc:
111 * @pool: the momory pool to destroy
112 * @size: size of the momory block
114 * Allocates a new block of memory in @pool. @size must
115 * be smaller than 256.
117 * Returns: the address of a newly allocated memory block.
120 mono_mempool_alloc (MonoMemPool *pool, guint size)
124 g_assert (pool != NULL);
126 size = (size + MEM_ALIGN - 1) & ~(MEM_ALIGN - 1);
128 if (pool->rest < size) {
130 MonoMemPool *np = g_malloc (sizeof (MonoMemPool) + size);
131 np->next = pool->next;
133 pool->d.allocated += sizeof (MonoMemPool) + size;
134 return (char *)np + sizeof (MonoMemPool);
136 MonoMemPool *np = g_malloc (MONO_MEMPOOL_PAGESIZE);
137 np->next = pool->next;
139 pool->pos = (char *)np + sizeof (MonoMemPool);
140 pool->rest = MONO_MEMPOOL_PAGESIZE - sizeof (MonoMemPool);
141 pool->d.allocated += MONO_MEMPOOL_PAGESIZE;
147 pool->pos = (char *)pool->pos + size;
153 * mono_mempool_alloc0:
155 * same as mono_mempool_alloc, but fills memory with zero.
158 mono_mempool_alloc0 (MonoMemPool *pool, guint size)
160 gpointer rval = mono_mempool_alloc (pool, size);
161 memset (rval, 0, size);