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(draw + 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
Faster and more efficient code can be written because pointers are closer to the hardware. That is, the compiler can more easily translate the operation into machine code. There is not as much overhead associated with pointers as might be present with other operators.
The first is that allocating global variables may be faster, since they are only allocated once, at the time the program is first spawned, whereas local variables must be allocated every time a function is called.
Using global variables causes very tight coupling of code. Using global variables causes namespace pollution. This may lead to unnecessarily reassigning a global value. Testing in programs using global variables can be a huge pain as it is difficult to decouple them when testing.
Execution time with pointers is faster because data are manipulated with the address, that is, direct access to memory location. Memory is accessed efficiently with the pointers.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With