fabian
fabian

Reputation: 13

Are many static variables in functions using up to much memory?

I want to write a cross-plattform wrapper for some OS specific (Linux/MacOSX/Windows) calls to get the number of cores of the CPU etc. My idea was to put all of them in single functions with static variables, so stuff like the number of cores that does not change will be processed only once.

int getNumCPUCores()
{
    static int numCores = 0;

    if(!numCores)
    {
        // The info is aquired here
    }        

    return numCores;
}

Now I wonder if this might be a bad idea, since all these static variables use up memory space whether they are initialized or not. Or did I misunderstand something?

Upvotes: 1

Views: 159

Answers (2)

Poni
Poni

Reputation: 11327

No it's fine, as James said.

Furthermore in order to avoid the need to use a mutual-exlusion object (if you plan to use it in a multi-threaded app!) you'd better have a static instance of a class that would assess the number of cores upon construction.

Upvotes: 0

James McNellis
James McNellis

Reputation: 355207

An int is a handful of bytes (four or eight on most modern platforms). Unless you have millions of static variables or static variables of some really huge type, you don't need to worry about it.

Upvotes: 5

Related Questions