Could it be beneficial to lazy instantiate members of a static class?

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?)

Answers


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.


Need Your Help

Exceeded maximum execution time in Google App Script with Contacts API

google-apps-script google-apps

I am creating an script responsible of generating a report containing info about a set of groups and its contacts in google app script.

Hook dll is generating both 32 and 64 bit logs

asp.net dll iis-7.5 dll-injection

I have an environment setup that monitors a sample dotnet application running under IIS. I am using hook, profiler and tracker dll's to monitor. The Hook dll is being used by w3wp process. But the ...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.