faster malloc anyone?

Larry McVoy larry at geowhiz.UUCP
Sat May 3 08:54:25 AEST 1986


[ munch.  Does this bug still exist???? ]

I was looking at the src for [cm]alloc() and came to the (hasty) conclusion
that they take to long for little memory requests.  It seems that they are 
leftover from the days of 256K unix systems where every byte counted.  With
workstations typically having gigabytes of vm and 2-4 megs of phys mem, it
seems that we might sacrifice some memory for speed.  In particular, if you
want to save strings (5-80 bytes), it seems wasteful to do a lot of work for
each call to strsav().  So, I wrote the following little chunks of code and
am requesting comments.  Can anyone point out why these are a *bad* idea 
(aside from the obvious upper bound problem)?  Another problem is that
free() won't work on these blocks...

new.h:
# define	BLKSIZ		8096
char* new();

utils.c:
/* utils.c -- strsav(), new() */
# include	"new.h"

    char*
strsav(s)
    register char* s;
{
    char* strcpy();
    register char* t;

    t = new(strlen(s) + 1);	/* strings smaller than BLKSIZ */
    return strcpy(t, s);
}


/*------------------------------------------------------------------02/May/86-*
 * new(size) - fast(??) memory allocator
 *
 * Inputs    -> (int)
 *
 * Returns   -> (char*)
 *
 * Results   -> The memory is allocated in big contiguous blocks via calloc(3).
 *		If the requst can fit in what's left of a block, then a block
 *		of the size requested is returned.  Otherwise, the rest of the
 *		block is discarded & a new block is allocated. 
 * 
 * Warning   -> This would seem to work great for little stuff.  Don't use it
 *		for big blocks.  Absolute largest allocatable block is BLKSIZ.
 *		For speed NO CHECK IS PERFORMED TO SEE IF THE REQUEST IS LESS
 *		THAN BLKSIZ.  BLKSIZ is guaranteed to be 1k or bigger (usually
 *		much bigger).
 * Revisions:
 *----------------------------------------------------------------------larry-*/
    char*
new(size)
    register unsigned size;
{
    register char* blk;
    static char* block = NULL;
    static unsigned bytes_left = 0;

    if (bytes_left < size)
	if (!(block = calloc(1, BLKSIZ)))
	    syserr("calloc in new");

    blk = block;
    block += size;
    bytes -= size;
}
-- 
Larry McVoy
-----------
Arpa:  mcvoy at rsch.wisc.edu                              
Uucp:  {seismo, ihnp4}!uwvax!geowhiz!geophiz!larry      

"Just remember, wherever you go -- there you are."
 	-Buckaroo Banzai



More information about the Comp.unix mailing list