Question

So, I have a class with members whom I am using more or less as constants. I cannot assign them as constants since they are more complex than a simple primitive. Therefore, these 'quasi-constants' are used repeatedly in various places in my application. Admittedly, I will likely move these to a configuration file in the future and have them loaded dynamically.

However, for now I was curious - that though these are served from a static class, could I at all benefit from wrapping them with lazy instantiation? The reason that I ask is because I do not make use of every 'quasi-constant' and there is some overhead associated with constructing each one (albeit very little). I do not expect any real gain by doing this, as it's not a bottleneck or anything, but I am curious as to best practices. I do not know enough about the internals of static classes to answer this myself. I do know that accessing static members does not require an instance of the class - though at some point it must be constructing those members. So my question boils down to this: when are static members of a static class constructed? If they are constructed prior to use, then could I at all benefit by lazy instantiation? (instantiating them only when they are requested?)

Was it helpful?

Solution

when are static members of a static class constructed?

The static constructor and all initialization occurs before the first instance of that class is created or any static members are referenced.

Typically, the static constructor and all static members are initialized immediately before the first time you refer to the class, though technically it can happen at any point prior to the first usage.

If they are constructed prior to use, then could I at all benefit by lazy instantiation? (instantiating them only when they are requested?)

You may benefit from this, particularly if the values require significant initialization or large memory usage, and may not always be used. The Lazy(Of T) class makes this fairly simple to implement.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top