C: Which is faster, accessing global variable or passing a pointer to the function
I am currently rewriting one of my programs. It has a heavily recursive function which solves peg-solitaire:
int solve(int draw) {
if (finished())
return true;
//loop over every possible move (about 76 long values)
//do a move (access the board, which is a long value)
if (solve(开发者_StackOverflowdraw + 1))
return true;
return false;
}
So i was wondering if it's faster to use solve like this:
solve(int draw, long **moves, long *board) {}
At the moment both moves and board are global variables.
Of course i am going to test it, but if someone tells me that this attempt isn't going to be efficient i will save some time :).
best regards
It probably won't be as efficient, but the only way to know for sure is to profile your code. If the bulk of your execution time is spent doing your actual game logic, then the tiny amount of overhead putting a few arguments on the stack should be negligible.
However, from a design point of view, avoiding global variables is much better. It allows your code to be stateless, and hence potentially re-entrant and thread-safe. However, this may or may not be relevant for your application.
I don't think this is the performance bottleneck.
The only thing that comes to my mind with the code you show is this:
Do you need long long variables? They usually need more space, which means more time to use them. I remember once I replaced double variables with float variables and I got a BIG boost (50% less execution time). This may help a little bit :)
This looks like optimizing too soon!
Every time you call solve(), you have to check if you are finished(). The cost of the finished() check is going to blow away any difference in variable access time.
Get it correct first, then profile it if it's too slow, then optimize!
There is certain overhead with passing parameters to function - writing parameters to stack. In majority (probably all) of modern architectures stack acess and global data access have the same speed, so most likely passing parameters will be a bit slower.
精彩评论