Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When Are Static Classes In .NET Loaded Into Memory?

Tags:

c#

.net

internals

As the title suggests, I am interested in when static classes are loaded into memory in .NET, C# in particular. I assume it is similar to this question in Java and this question regarding static methods, in that it is loaded the first time it is used. Additionally, once it is in memory does it stay there until the application terminates or does is get cleaned up when the garbage collector comes along to clean up the class that used it?

I realize the small amount of memory a static class uses is not terribly important in a world of computers that have 8+GB of RAM standard, but it is always interesting to know the internals.

Edit:

The answers led me want to add more to this question and to clarify with an example. If I understand correctly, in the example below Contraption.SomeString will be placed in memory first followed closely by Contraption.AnotherString with the first time through the loop.

public static class Contraption
{
    public static string SomeString = "Some String";
    public static string AnotherString = "Another String";
}

public class Processor
{
    public void Process(List<SomeClass> items)
    {
        foreach(var item in items)
        {
            if(item.Name == Contraption.SomeString)
            {
                //do something
            }
            if(item.Name == Contraption.AnotherString)
            {
                //do something
            }
        }
    }
}
like image 816
ninja coder Avatar asked Jan 14 '17 01:01

ninja coder


People also ask

Where are static classes stored in memory?

Singleton objects are stored on the heap while static classes are stored on the stack. How is memory allocated for a static variable? Static variables are stored on the heap, regardless of whether they are declared as a reference type or a value type.

Where static methods are stored in memory in C#?

Static methods as well as static variables are stored in the heap memory, since they are part of the reflection data (class related data, not instance related).

Do static classes take up memory?

Static data and static methods do not take up memory in individual instances.

How a class is loaded into memory?

Java classes aren't loaded into memory all at once, but when required by an application. At this point, the Java ClassLoader is called by the JRE and these ClassLoaders load classes into memory dynamically. Not all classes are loaded by a single ClassLoader.


2 Answers

Regarding static fields initialization, an important point is the usage of static constructor. The CLR has a class loader component, which loads a class (metadata information) and request for memory allocation from the memory manager as they are used in the program. Metadata loading is one time job, post it just request memory on need basis

As understood in the discussion, the static class variables are loaded on the first usage of the class anywhere, and are assigned the memory, but using the static constructor can ensure that they are initialized as the first thing when class loader is invoked, its a one time call, which can do the initialization of all the static variables in a class, this even precede the first usage policy, as its when CLR (mscoree.dll) is components are loaded for a given program.

Static constructor is never called after first time under any circumstance (except program restart), even if there's an exception, its quite widely used, also static variables can be collected by setting them as null

like image 188
Mrinal Kamboj Avatar answered Oct 05 '22 23:10

Mrinal Kamboj


I assume you're referring to fields within static classes (or static fields in non-static classes). They will be initialized before the first use. It's described in the C# specification:

10.4.5.1 Static field initialization

The static field variable initializers of a class correspond to a sequence of assignments that are executed in the textual order in which they appear in the class declaration. If a static constructor (Section 10.11) exists in the class, execution of the static field initializers occurs immediately prior to executing that static constructor. Otherwise, the static field initializers are executed at an implementation-dependent time prior to the first use of a static field of that class.

Static class members are considered Garbage Collection roots and all always reachable.

You can force the objects to be reclaimed by resetting the static member to null or other object:

public static class Foo 
{
    public static object Bar = new object();
}

// somewhere later
Foo.Bar = null;
// the object can be collected now.
like image 30
MarcinJuraszek Avatar answered Oct 06 '22 00:10

MarcinJuraszek