C

Asked • 06/12/19

Why malloc+memset is slower than calloc?

It's known that `calloc` is different than `malloc` in that it initializes the memory allocated. 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 code for a benchmark.The result is confusing.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++; } }Output of Code 1: 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++; } }Output of Code 2: time ./a.out **real 0m2.693s** user 0m0.973s sys 0m1.721s Replacing `memset` with `bzero(buf[i],BLOCK_SIZE)` in Code 2 produces the same result.**My question is:** Why is `malloc`+`memset` so much slower than `calloc`? How can `calloc` do that?

2 Answers By Expert Tutors

By:

Keith B. answered • 07/05/19

Tutor
4.6 (22)

Software Engineer and Math Geek

Still looking for help? Get the right answer, fast.

Ask a question for free

Get a free answer to a quick problem.
Most questions answered within 4 hours.

OR

Find an Online Tutor Now

Choose an expert and meet online. No packages or subscriptions, pay only for the time you need.