calloc v/s malloc and time efficiency

yCalleecharan picture yCalleecharan · Apr 9, 2010 · Viewed 21.7k times · Source

I've read with interest the post C difference between malloc and calloc. I'm using malloc in my code and would like to know what difference I'll have using calloc instead.

My present (pseudo)code with malloc:

Scenario 1

int main()
{  
   allocate large arrays with malloc

   INITIALIZE ALL ARRAY ELEMENTS TO ZERO

   for loop //say 1000 times
    do something and write results to arrays
   end for loop

   FREE ARRAYS with free command

} //end main

If I use calloc instead of malloc, then I'll have:

Scenario2

int main()
{  

   for loop //say 1000 times
    ALLOCATION OF ARRAYS WITH CALLOC 

    do something and write results to arrays

    FREE ARRAYS with free command

   end for loop


} //end main

I have three questions:

  1. Which of the scenarios is more efficient if the arrays are very large?

  2. Which of the scenarios will be more time efficient if the arrays are very large?

  3. In both scenarios,I'm just writing to arrays in the sense that for any given iteration in the for loop, I'm writing each array sequentially from the first element to the last element. The important question: If I'm using malloc as in scenario 1, then is it necessary that I initialize the elements to zero? Say with malloc I have array z = [garbage1, garbage2, garbage 3]. For each iteration, I'm writing elements sequentially i.e. in the first iteration I get z =[some_result, garbage2, garbage3], in the second iteration I get in the first iteration I get z =[some_result, another_result, garbage3] and so on, then do I need specifically to initialize my arrays after malloc?

Answer

RarrRarrRarr picture RarrRarrRarr · Apr 9, 2010

Assuming the total amount of memory being initialized in your two examples is the same, allocating the memory with calloc() might be faster than allocating the memory with malloc() and then zeroing them out in a separate step, especially if in the malloc() case you zero the elements individually by iterating over them in a loop. A malloc() followed by a memset() will likely be about as fast as calloc().

If you do not care that the array elements are garbage before you actually store the computation results in them, there is no need to actually initialize your arrays after malloc().