static variables in function

Hi,

I'm not sure which influence static variables has to cache performance.
This may be bad programming, but I'm just curious to know whether this can
have influence on the performance.
As I know, the static variables belongs to a storage class (not to be confused with classes in object-oriented programming) like extern.
Dynamic variables are cache-safe, while static variables are not. I'm not sure what that means, because some says that the object will not be cache-safe.

An example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include <iostream>

class myClass {
 private:
  int x;
 public:
  myClass() {this->x=0;}
  ~myClass() {}

  int count(void) {
    static bool k(false);

    if(k) {
      k=false;
      x=x*2;
      return(x);
    }
    else {
      k=true;
      return(++x);
    }
  }
};

int main(void) {
 myClass myObject = myClass();

 for(size_t i=6;i--;)
    std::cout << myObject.count() << ", ";

 
 return(1);
}


The output would be 1, 2, 3, 6, 7, 14,.

The question is. Should I put the k variable as a dynamic variable declared in the class' private scope? Could this give a better performance doing this?

I hope this question is not too nerdy..

/Jesper
No idea what you mean by "cache-safe" in this context, but...
k should be part of the class, because static variables are shared between all instances of the class. That would result in disaster in the case of multiple instances and different threads (or: recursive calls or calls of the same function on another instance in the same thread or different threads).

In theory, it's the faster solution as well, since k can be... somewhere in memory, whereas as a class member it'll right next to x in memory. Since x is accessed anyway, this improves locality of reference.
I daresay you can't even measure the difference in practice, though. This is pure micro-optimization + premature optimization.
Well Thanks for the explanation. It was just what I needed :-)

I understand why you are not sure what cache-safe means in this case. It was just something I read in another thread. But I think it means that a static variable can be seen as a global variable that all instances have access to.

So I see your point. If I have more than one object of the myClass, it could be a problem. Especially a disaster in multithreading. Hmm.. That is a good point to avoid static variables in functions.

Its just that I'm looking at some C code some physicists have made. And they love statics and macros, Yrrgh! I have to convert it into C++ with an eye for multithreading. Thats a hell of a job.
Topic archived. No new replies allowed.