On Wed, 11 Feb 2004 22:14:32 GMT, hello smith
<ih***********@ ihatespammers.c om> wrote:
I have a lot of functions that add values to an array. They alos update
a global variable of type int. Currently, I use a global variable to
hold this array. All functions access this array global variable and
add their values. Then they increment the global int variable.
Is it faster to pass the array and the int variable by reference to each
function or just access the global variables?
I have tried using gprof, I did not get anything that suggested either ways.
Thanks in advance for any help.
[I wouldn't be surprised if there's a FAQ entry on this, but I feel
like typing ;-) ]
There are two separate issues here, IMO relating to:
1. performance - of lesser impact
2. style/clarity/maintainability - of greater impact (okay, it is a
"compound" issue...)
Performance-wise, passing pointers to both the array (in the form of a
pointer to its first element, probably) and the counter has a cost in
terms of function call overhead (a call, arg passing, and return each
time), and then each access of data in the array or the counter
(within the function) will probably cost "a little bit more" than if
you were accessing the items by their own names in those places where
they're in scope (by virtue of the indirection necessary there.)
I'm not surprised you didn't see much difference when profiling,
though; I'd guess that there's enough other computation going on such
that the extra cost is comparatively negligible.
Which brings me to issue #2: If the program would become more
maintainable by encapsulating all the manipulations of that array (and
its associated counter) within that function, then /you/ have to
decide whether or not the price is worth it under your particular
circumstances.
Leor Zolman
BD Software
le**@bdsoft.com www.bdsoft.com -- On-Site Training in C/C++, Java, Perl & Unix
C++ users: Download BD Software's free STL Error Message
Decryptor at
www.bdsoft.com/tools/stlfilt.html