I never looked at the disassembly, no. Generally speaking the normal cost of a function static variable should be an unsynchronized comparison. If the variable says it isn't initialized it locks a mutex, checks again to prevent a race condition, initializes the object if it wasn't and then flags it as initialized, then unlocks. For all following calls the unsynchronized comparison will result in it not jumping to the init code. Total cost after the first call: 1-2 clock cycles. Could even be free in follow up calls if the C++ compiler is willing to patch the initial function.Graf Zahl wrote:Have you ever looked at the mess of code that's involved with this?
I'm not 100% sure, but I believe C# static constructors are initialized the same way. First time any static functions or variables are accessed it calls the constructor. Probably implemented in a similar way.
In some situations the static variables in a function can actually be faster - mostly because they aren't initialized unless the function is actually called. Global static variables always are initialized on startup.
In any case, I think the real problem with global variables are the destructors. Because they aren't allowed to call anything else global there's very little stuff they can actually do. This problem exists no matter how you declare them, inside a function or not. The C++ runtime implementations in particular are having problems with this. It used to be extremely easy to crash them, just create a static std::thread or something else that usually talks to some subsystem in its destructor.