473,804 Members | 3,494 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Globals vs passing in by reference

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.

Nov 14 '05 #1
4 2500
In article <cP************ ******@bgtnsc05-news.ops.worldn et.att.net>,
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.


Then most likely it doesn't make a measurable difference.

Does anyone complain that your program is too slow? Will anyone give you
lots of money if it runs faster?
Nov 14 '05 #2
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
Nov 14 '05 #3
hello smith wrote:
I have a lot of functions that add values to an array.
They also 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.
That's a *very* bad idea.
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.
It sounds like you just answered your own question.
cat main.c #include <stdio.h>

typedef struct Pair {
int* A; // pointer to array
int I; // integer
} Pair;

inline
Pair Pair_create(int * array, int i) {
Pair p;
p.A = array;
p.I = i;
return p;
}

inline
int Pair_total(cons t Pair* pP) {
return pP->I;
}

inline
Pair* Pair_modify(Pai r* pP) {
(pP->A)[pP->I] = pP->I;
++(pP->I);
return pP;
}

int Pair_fprintf(FI LE* fp, const Pair* pP) {
int characters = fprintf(fp, "%d\n", pP->I);
for (int j = 0; j < pP->I; ++j)
characters += fprintf(fp, "%d\t%d\n", j, pP->A[j]);
return characters;
}

int main(int argc, char* argv[]) {
const
int n = 256;
int array[n];
Pair p = Pair_create(arr ay, 0);
for (int j = 0; j < n; ++j)
Pair_modify(&p) ;
Pair_fprintf(st dout, &p);
return 0;
}
gcc -Wall -std=c99 -pedantic -o main main.c> ./main

256
0 0
1 1
Nov 14 '05 #4
hello smith 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.


It is the strong belief of many that global variables should be avoided
in nearly all situations. Also, C does *not* pass values by reference.
Performance should be of little concern to you in this particular area.
A program written with a large number of global variables can be very
tedious to maintain.

Nov 14 '05 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

45
2686
by: It's me | last post by:
I am new to the Python language. How do I do something like this: I know that a = 3 y = "a" print eval(y)
2
1399
by: Ron_Adam | last post by:
Using this example: def whatisx(): try: print 'x is',x except: print 'There is no x'
11
2858
by: Matt | last post by:
Hello, I'm rather new to C++ and have a question about globals. What is the big deal about them? They make things much easier to program because you don't have to worry about all the passing back and forth between functions. And, if you are going to give the reason about "it makes it easier to debug your program if you don't use globals" well to that I say, how so? Yes, not using globals prevents a random function from setting...
58
10188
by: jr | last post by:
Sorry for this very dumb question, but I've clearly got a long way to go! Can someone please help me pass an array into a function. Here's a starting point. void TheMainFunc() { // Body of code... TCHAR myArray; DoStuff(myArray);
2
1657
by: DFS | last post by:
Not sure whether it's bad programming practice or not, but I have a module of globals I declare in each system: Global ws As Workspace Global db As Database Global td As TableDef Global rs As Recordset, rs1 As Recordset Global rs2 As Recordset, rs3 As Recordset Global ctl As Control Global frm As Form, subFrm As Form
8
2118
by: Dennis Myrén | last post by:
I have these tiny classes, implementing an interface through which their method Render ( CosWriter writer ) ; is called. Given a specific context, there are potentially a lot of such objects, each requiring a call to that method to fulfill their purpose. There could be 200, there could be more than 1000. That is a lot of references passed around. It feels heavy. Let us say i changed the signature of the interface method to:
6
6002
by: MSDNAndi | last post by:
Hi, I get the following warning: "Possibly incorrect assignment to local 'oLockObject' which is the argument to a using or lock statement. The Dispose call or unlocking will happen on the original value of the local." My code is: using System; using System.Collections.Generic;
3
2000
by: ojorus | last post by:
Hi! Just two short questions..: 1) In a function I want to get the value of a global variable declared outside the function. Should I use "global $variable" or $GLOBALS? Are there any differences in performance or other aspects which should make me choose the one thing or the other? 2) Generally, is it better to pass arguments to the function instead?
17
1285
by: meridian | last post by:
I thought I had 'got' globals but this one seems strange. I want my example function 'doIt' to use and optionally modify a module variable 'gname', so I declare 'global gname' in the function, but when modified it doesn't stay modified. gname = 'Sue' def doIt(name = gname): global gname gname = name print 'doIt name', name, 'gname', gname
0
9704
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9572
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10562
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10303
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9132
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6845
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5508
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5639
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
2978
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.