0

If I'm using function Foo() a lot of times, and Foo() uses a temporary array, which of the two is more efficient:

1)

void Foo()
{
  int arr[BIG_NUM];
  ...
}

OR:

2)

void Foo(int n)
{
  int* arr;
  ...
  arr = (int*)malloc(n*sizeof(int));
  ...
  free(arr);
}
Filipe Gonçalves
  • 20,783
  • 6
  • 53
  • 70
cookya
  • 3,019
  • 7
  • 26
  • 37
  • Not only is the first version faster, it also is conceptually much simpler. That alone would be a reason to prefer it. Nitpick: functions in C without arguments should have `void` as the parameter list: `void Foo(void)` – Jens Gustedt Apr 28 '14 at 09:39
  • 1
    These two functions are not functionally identical - in the second one, the array length is supplied by user, and in the first one, you hope it's big enough. While the first one is faster, note there are other things to consider. – milleniumbug Apr 28 '14 at 09:52

3 Answers3

3

The former will probably be a lot more efficient.

You should always avoid going to the heap henever possible. Stack allocation is on the order of a single instruction, so it's really negligble. Heap allocation can cost thousands (or more) times that, easily.

Also, don't cast the return value of malloc() in C.

Community
  • 1
  • 1
unwind
  • 391,730
  • 64
  • 469
  • 606
0

The first one with array on the stack is more efficient, because heap allocation is much more costly than stack allocation.

Wojtek Surowka
  • 20,535
  • 4
  • 44
  • 51
0

The dynamic allocation calls a function to allocate memory, and obviously you will need to check the return value too and then another function to deallocate. The stack allocation is faster for this case. Depending on your situation maybe a global array would be even faster.

Ferenc Deak
  • 34,348
  • 17
  • 99
  • 167