Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C99 variable length automatic array performance

Tags:

performance

c

Is there significant cpu/memory overhead associated with using automatic arrays with g++/Intel on 64-bit x86 linux platform?

int function(int N) {
    double array[N];
  • overhead compared to allocating array before hand (assuming function is called multiple times)

  • overhead compared to using new

  • overhead compared to using malloc

The range of N may be from 1kb to 16kb roughly, stack overrun is not a problem.

like image 254
Anycorn Avatar asked Jun 10 '10 22:06

Anycorn


2 Answers

The difference in performance between a VLA and a statically-sized array should be negligible. You may need a few extra instructions to calculate how much to grow the stack but that should be noise in any real program.

Hmm, on further thought, there could also be some overhead depending on how the local variables are layed out in memory and whether there are multiple VLAs.

Consider the case where you have the locals (and assume they are put in memory in the order they are specified).

int x;
int arr1[n];
int arr2[n];

Now, whenever you need to access arr2, the code needs to calculate the location of arr2 relative to your base pointer.

like image 161
R Samuel Klatchko Avatar answered Sep 30 '22 01:09

R Samuel Klatchko


It is kind of what alloca is doing.

  • http://www.gnu.org/s/libc/manual/html_node/Variable-Size-Automatic.html#Variable-Size-Automatic
  • http://www.gnu.org/s/libc/manual/html_node/Advantages-of-Alloca.html
  • http://www.gnu.org/s/libc/manual/html_node/GNU-C-Variable_002dSize-Arrays.html#GNU-C-Variable_002dSize-Arrays
like image 31
Albert Avatar answered Sep 30 '22 00:09

Albert