Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does function parameters and local variables affect on the performance of a C program [closed]

Tags:

performance

c

is it worth to reduce the number of function parameters and local variables to enhance the performance of a C program?

in the provided code below, maybe the example doesn't make a difference if the function is called few times during the execution but maybe it make sense if it's called n times, so is there any performance benefits in this case?

int n[4];
// read numbers ...

do_sum1(n[0], n[1], n[2], n[4]);
do_sum2(n);

// Functions definition
// --------------------
void do_sum1(int a, int b, int c, int d)
{
  printf("%d\n", a + b + c + d);
}

void do_sum2(int n[4])
{
  printf("%d\n", n[0] + n[1] + n[2] + n[3]);
}
like image 434
XBlueCode Avatar asked Jan 25 '23 21:01

XBlueCode


1 Answers

The question is trickier than it seems.

First of, let's assume the function is not inlined (as otherwise they are more than likely to be compiled to the same code) and let's analyze the effect.

From one hand, the number of parameters to function affects the performance. All other things being equal, the more parameters are passed, the worse the performance - since copying parameters to the place function expects to find them (be it a stack, a register or any other storage) takes non-0 time.

From the other hand, semantic matters, and in this particular case, things are not equal! In your first case, you are passing 4 integer parameters. Assuming AMD64 ABI, they will be passed in CPU registers - which are super-fast to be accessed for both reading and writing.

However, in the second case you are effectively passing a pointer to a memory location. Which means, accessing values through this pointer means indirection, and at best the values would be found in L1 CPU cache (most likely), but at worst will be read from main memory (super slow!). While L1 cache is fast, it is still much slower when compared to register access.

Bottom line:

I expect the second case to be slower, than the first one.

like image 115
SergeyA Avatar answered Jan 28 '23 11:01

SergeyA