On Wed, 13 Jun 2007, Ed Schouten wrote:

* Garrett Cooper <[EMAIL PROTECTED]> wrote:
 Garrett Cooper wrote:
   Title says it all -- is there a particular reason why malloc/bzero
should be used instead of calloc?
-Garrett
 As someone just brought to my attention, I should do some Googling.

 Initial results brought up this:
 <http://boredzo.org/blog/archives/2006-11-26/calloc-vs-malloc>.

To be more precise; I took a look at the source code of calloc on my
FreeBSD 6 box:

| void *
| calloc(num, size)
|         size_t num;
|         size_t size;
| {
|         void *p;
|
|         if (size != 0 && SIZE_T_MAX / size < num) {
|                 errno = ENOMEM;
|                 return (NULL);
|         }
|
|         size *= num;
|         if ( (p = malloc(size)) )
|                 bzero(p, size);
|         return(p);
| }

This means that the results on that website would be quite different
than the the ones that the FreeBSD 6 malloc/calloc should give. There is
even a difference between calloc'ing 10 block of 10 MB and 1 block of
100 MB, which shouldn't make a difference here. calloc doesn't have any
performance-advantage here, because it just calls malloc/bzero.

When looking at FreeBSD -CURRENT's calloc (won't paste it; too long), it
just does a arena_malloc/memset (which is malloc/bzero) for small
allocations but a huge_malloc for big allocations (say, multiple pages
big). The latter one already returns pages that are zero'd by the
kernel, so I suspect the calloc performance for big allocations on
-CURRENT is a lot better than on FreeBSD 6. As with FreeBSD 6, it
wouldn't matter if you calloc 10 pieces of 10 MB or one piece of 100 MB.

Yours,
--
Ed Schouten <[EMAIL PROTECTED]>
WWW: http://g-rave.nl/

Hmmm... I wonder what the Mach kernel in OSX does to allocate memory then. I'll 
have to take a look at OpenDarwin's source sometime and see what it does.

-Garrett

_______________________________________________
freebsd-hackers@freebsd.org mailing list
http://lists.freebsd.org/mailman/listinfo/freebsd-hackers
To unsubscribe, send any mail to "[EMAIL PROTECTED]"

Reply via email to