user997112
user997112

Reputation: 30615

Accessing global array more efficient than passing as argument?

I have a function which is called many times and I need to pass an array of 4 or 5 elements down in to 3 or 4 nested functions.

Surely it would be more efficient to create this array data structure as a global variable where all functions can access it with one address reference, rather than passing it down the nested functions as an argument. The latter would require stack pushing and popping whereas the global variable wouldn't?

(I know I can profile, but I want to understand what the theory would suggest- the difference in what code would be executed)

Upvotes: 0

Views: 1220

Answers (2)

Amir ElAttar
Amir ElAttar

Reputation: 99

1-first of all an array in C/C++ is just a contiguous area reserved in memory , with a pointer to the first element namely : Arr[0]

2-passing array as a parameter most likely consumes a register in parameter passing (according to calling convention used and count of function parameters) while using a global variable will not consume this register

3-to the compiler passing the parameter like

a) Foo(int* Arr)
b) Foo(int Arr[])

is just the same, a pointer is copied to the register or the stack according to calling convention used

the format in (b) may just give a hint to the compiler that there are no overlapping while processing the array to make better optimization

Upvotes: 1

Anil8753
Anil8753

Reputation: 2735

You can use pointer or reference instead of passing whole array. If it is C plus plus, make that array member variable.

Upvotes: 0

Related Questions