This question is mostly related to the way language implementer do implements static class initalization (pretty specialized question). It is for curiosity and also to potentially improve my code to gain few nanoseconds
For most object oriented language I know (C++, C#, Java), there is a possibility to define a static constructor and/or static member definition with initialization values.
A language definition could initialize class level static parts:
- First use of a dll or exe (module load) and in module order of compilation (I think C++)
- First usage of the class. (I think C# and Java)
- Potentially other obscurs ones ???
I think that experience showed that it is a lot preferable to initialize static parts on first usage of the object in order to ensure proper precedence of dependencies between classes.
But using static parts initialization on first usage of a class would appears to me to add a hit in performance to any class. That is because on: each call to a constructor, or each call to a static member or functions, the language will have to check if the static initializer has been run prior to give access to them.
So, is there a way (a twist), a language implementation could do to prevent this performance hit, and if yes how?
In the same time... Depending on implementation, can we get class performance improvement by not using any static parts (member, constructor) for that class? I mean compiler will know that for that class, runtime does not have to check if static initalizer has already been call.
Just to be more clear, to ask in another way:
The problem with static initalization is because it need to be called only once for the lifetime of an application and only once. In modern language (C# and Java), it is called on first usage of that class (any usage, static member usage or instance constructor) could trigger the static initialization. But it has to be done only once. So does the compiler check that on each and every static access to that class and/or to any constructor call? Or does the compiler does a magic trick to prevent that (check on each and every call to static member and/or constructor call)?