Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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(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

like image 442
imbaer Avatar asked Oct 16 '10 11:10

imbaer


People also ask

How are pointers faster than variables?

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.

Are global variables faster?

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.

Is it better to use more number of global variables as they can be easily accessed from different routine?

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.

Is using pointers faster than using direct addressing?

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.


1 Answers

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.

like image 138
Oliver Charlesworth Avatar answered Sep 20 '22 10:09

Oliver Charlesworth