79401

The cost of memory allocation in a loop in C

Question:

Is there a significant difference between allocating an array inside or outside a loop in terms of cost of time?

I use many arrays in functions inside a loop in my program, should I pass all the arrays as function parameters to increase the performance although it decreases the readability? For example:

#include <stdlib.h> #define N 1000000 void foo() { int* array = (int*)malloc(N*sizeof(int)); /* Do something with the array */ free(array); } int main() { int i; for(i=0; i<1000000; i++) foo(); return 0; }

or

#include <stdlib.h> #define N 1000000 void foo(int* array) { /* Do something with the array */ } int main() { int i; int* array = (int*)malloc(N*sizeof(int)); for(i=0; i<1000000; i++) foo(array); free(array); return 0; }

Answer1:

The cost of a memory allocation is not very dependent on the size of the allocation. Roughly speaking, a memory allocation of any size is O(1), and obviously standard libraries are optimized to make allocations as fast as possible.

So if you need a very big allocation, as in the example program, the cost of allocation will be trivial compared with the cost of initializing the allocated memory (to say nothing of the cost of actually doing the computation which is required).

For small allocations in very tight loops, where the allocation overhead might be noticeable, alternative mechanisms might be useful; one of these is the one suggested in the question, passing a preallocated array as an additional parameter to the function. (Other possibilities include using C's variable length arrays (VLAs), if they are available on all target platforms, or alloca/_alloca/_malloca.)

But I would suggest not implementing microoptimizations of this form until there is solid evidence that the time savings are justified; otherwise, the cost in maintainability and readability will outweigh any small time savings you might achieve.

Answer2:

The second example is better with regards to time. Assuming the thing you would do with the array in 'foo' for each example is the same.

In the second example: You allocate one array, and do something to it a bunch of times. Then after you do that destroy it.

In the first example: each iteration of the loop you create a new array, do something and then destroy it. This means that extra time is taken to create and destroy the array each iteration of the loop.

Answer3:

Declaring the array and then using it strikes me as the better way to do things.

Your declaration takes place in a higher-level body of code and happens once: therefore it is easy to understand what is going on, change the allocation size, handle allocation errors, and debug.

Declaring the array in the for loop raises a definite <a href="https://en.wikipedia.org/wiki/Code_smell" rel="nofollow">code smell</a> for me: it is a solution that lacks modularity.

Recommend

  • make_shared with custom new operator
  • iPhone: Existence of a Memory Leak Profiler?
  • Copy current CLOB column to new BLOB column in Oracle
  • Multiple instances of _CDSnapshot_[entityName]_
  • Julia : BLAS.gemm!() parameters
  • Keep playing a sound over and over again in Matlab?
  • Is there a way to group nth-child CSS rules for same parent
  • Return value syntax in java
  • Rails + Amazon RDS : latency issues
  • Why integer division and modulo isn't optimized out in NVRTC
  • Making a vectorized numpy function behave like a ufunc
  • dynamic server time
  • Git: failed to read object … Invalid argument
  • Catching exceptions caused in different threads [duplicate]
  • include dlls in visual studio c++ 2008
  • react split panel resize
  • Can you pass an array from javascript to asp.net mvc controller action without using a form?
  • Check all values in string[] for length?
  • DIV instruction jumping to random location?
  • Date Conversion from yyyy-mm-dd to dd-mm-yyyy
  • How to use carriage return with multiple line?
  • Is there a way to do normal logging with EureakLog?
  • jQuery .attr() and value
  • why overloaded new operator is calling constructor even I am using malloc inside overloading functio
  • Asynchronous UI Testing in Xcode With Swift
  • Control modification in presentation layer
  • JavaScriptCore crash on iOS9
  • output of program is not same as passed argument
  • Can I have the cursor start on a particular column by default in jqgrid's edit mode?
  • Large data - storage and query
  • Timeout for blocking function call, i.e., how to stop waiting for user input after X seconds?
  • Adding custom controls to a full screen movie
  • Akka Routing: Reply's send to router ends up as dead letters
  • Confusion with PayPal's monthly billing cycle
  • unknown Exception android
  • Checking variable from a different class in C#
  • Django query for large number of relationships
  • Why is Django giving me: 'first_name' is an invalid keyword argument for this function?
  • How can I use `wmic` in a Windows PE script?
  • How to push additional view controllers onto NavigationController but keep the TabBar?