why malloc+memset slower than calloc?
- by kingkai
It's known that calloc differentiates itself with malloc in which it initializes the memory alloted. With calloc, the memory is set to zero. With malloc, the memory is not cleared.
So in everyday work, i regard calloc as malloc+memset.
Incidentally, for fun, i wrote the following codes for benchmark. The result is confused.
Code 1:
#include<stdio.h>
#include<stdlib.h>
#define BLOCK_SIZE 1024*1024*256
int main()
{
int i=0;
char *buf[10];
while(i<10)
{
buf[i] = (char*)calloc(1,BLOCK_SIZE);
i++;
}
}
time ./a.out
real 0m0.287s
user 0m0.095s
sys 0m0.192s
Code 2:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define BLOCK_SIZE 1024*1024*256
int main()
{
int i=0;
char *buf[10];
while(i<10)
{
buf[i] = (char*)malloc(BLOCK_SIZE);
memset(buf[i],'\0',BLOCK_SIZE);
i++;
}
}
time ./a.out
real 0m2.693s
user 0m0.973s
sys 0m1.721s
Repalce memset with bzero(buf[i],BLOCK_SIZE) in Code 2 produce the result alike.
My Question is that why malloc+memset is so much slower than calloc? How can calloc do that ?
Thanks!