Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Speed and array passing

Status
Not open for further replies.

Disruptive

Programmer
Mar 8, 2005
40
GB
Hi

I have some simulation code which passes all arrays by reference to the required function block. I have avoided global variables even though this would be the easiest method and therefore I have functions which are being send maybe 10-15 arrays and the headers are quite cumbersome. However my key question is speed/efficiency. I am concerned that I may have been able to gain a speed advantage by using global variables? Do you think this is the case?

Thx
 
If you use global variables, you'd be eliminating some extra push/pop instructions, so I don't see any reason why it wouldn't be a little faster. Although, the difference probably wouldn't be noticable unless you were calling your function billions of times.
 
And think about readiness and maintenability of your code with global variables: that's the cost of optimization.

Cheers,
Dian
 
If you use a decent naming convention global variables shouldn't be a problem. Some people begin all globals with g_. Others have 3-4 letter mnemonics for each file and begin them with those 3-4 letters.

Another alternative is to put all the globals into a structure and then pass a pointer to the structure round. Saves having lots of parameters. Maintenance is simple: just add a new variable to the structure and use it wherever you want. No change to the interfaces anywhere.
 
Following on from xwd's point, if you need to pass lots of arrays around then that suggests that they could be seen as a single item or object of some kind.
That being the case, a structure would be the right solution.
You would not have to make that structure global, you could create it in stack space as normal and just pass a pointer to the structure around. Then you have just one pointer to pass.

Globals are a bad idea for a number of reasons.
As an example, if you ever want to package up your code and use it as a module or (dare I say it), more like an object then you're stuck with only one structure. If you create your structures on the stack, you can have as many as you like (within reason of course!).


Trojan.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top