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
}
}
}
}
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
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.
Static variables persist for the lifetime of an AppDomain, and in .NET, you can have multiple AppDoamins per application. Although most of the time, it is just one AppDomain per application, and other AppDomains are mostly created for sandboxing plugins.
https://msdn.microsoft.com/en-us/library/2bh4z9hs(v=vs.110).aspx
Related
A couple of days ago I asked myself about the difference, if any, between initializing static fields via
the static constructor and doing so by using a static field initializer (inline initialization of a static field at the point of declaration).
After reading plenty of stackoverflow questions on the subject and the famous Jon Skeet's article on the beforefieldinit flag I've now a much better understanding of the difference between the two initialization strategies.
There is one point that I'm not sure about, mostly because I wasn't able to find any official documentation about it.
The static construcutor is guaranteed to be executed only once and I think this holds true even in multi threading scenarios (when different threads create instances of the class and / or use static members of the class. In any case, the static constructor runs once and only once).
Is this true even for the inline initialization of the static fields ? Is the inline initialization of a static field guaranteed to be executed once even in multi threaded scenarios ?
Another point I'm still missing is what are the practical consequences of this difference in the initialization of the static fields of a class. Put another way, I would like to understand when the correctness of a piece of code can be affected by the choice of initializing a static fied inline at the point of declaration (instead of using the static constructor).
Most of the time (this depends mostly on the type of code that I usually work on, namely web applications) I use static readonly fields in service classes to store things that are used by the service I'm writing to perform computations or taking decisions. I decide to put these things inside static fields because they need to be the same for all the possible instances of the class I'm writing, they are actually invariants that don't belong to a particular instance, but instead they belong to the algorithm itself.
This is an example:
public class SomeInterestingService
{
private static readonly int ConstantNumber = 13;
private static readonly string[] Names = new[] { "bob", "alice" };
private readonly INumberGenerator numberGenerator;
public SomeInterestingService(INumberGenerator numberGenerator)
{
this.numberGenerator = numberGenerator ?? throw new ArgumenNullException(nameof(numberGenerator));
}
public int ComputeMagicNumber()
{
int answer = this.numberGenerator.GetNumber();
foreach(var name in names)
{
answer += name.Length;
}
answer += ConstantNumber;
return answer;
}
}
In code like this, is there any practical difference in chosing static constructor initialization or inline initialization of the static fields ConstantNumber and Names, apart from the difference in performance (inline initialization is more performant due to runtime optimizations that are not possible when using the static constructor) ?
Can the correctness of the code above be affected by the coiche in any strange corner case ? (I think not)
Original question:
In code like this, is there any practical difference in chosing static
constructor initialization or inline initialization of the static
fields ConstantNumber and Names, apart from the difference in
performance (inline initialization is more performant due to runtime
optimizations that are not possible when using the static constructor)
?
The answer is no. Either those properties are set upon each construction of the class (instance properties) or set upon the first call to any of the members or methods to the class (static properties).
What #Henk Holterman is saying that because the array of names is a reference type you could theoretically change any of the values in the array. Like:
Names[0] = "Henk Holterman";
Even though the property is readonly. Meaning, you can't assign a new instance of array to that property. The values in the array are not readonly. And could be manipulated if public or by calling a method of that class.
Consider the following class snippet with two static member variables:
public static class Foo
{
static string A = GetA(B);
static string B = "required for A";
...
Now, my understanding is that A and B will be initialized when they are accessed for the first time. However, when I executed a fully-realized version of the snippet above where A was accessed before B was initialized, it led to null being passed in to GetA() instead of "required for A". Why isn't the behaviour to start initializing A, then, when it's realized that B is required to initialize A, initialize B, then return to finish the initialization of A?
What are the general rules around this? Why does it behave this way? I've seen other questions that touch on this (When do static variables get initialized in C#?) but they don't answer this question exactly. What is the static variable initialization order in C#? talks primarily about how this works across classes, not within a single class (though Jon Skeet's addendum to his answer -- "By popular demand, here was my original answer when I thought the question was about the initialization order of static variables within a class:...." does answer this question, it's buried in a much longer answer).
In short, don't do this.
Standard ECMA-334 C# Language Specification
15.5.6.2 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 (§15.5.6.1). Within a
partial class, the meaning of "textual order" is specified by
§15.5.6.1. If a static constructor (§15.12) 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
The fix is to :
Put them in the order and use Static Constructor,
or just Initialise them in a Static Constructor in turn giving you the ability to control the order of initialisation (given the above information).
Personally i suggest to Initialise them in a Static Constructor, it seems to make it more concrete and understandable, and less likely to be bumped in refactoring
I'm currently looking at some old code and I've come across a class that is using a private static property which is created with a default value and never modified; something like this -
public class Foo
{
private static readonly string ConnectionString = ConfigurationManager.ConnectionStrings["SqlConnection"].ToString();
public Bar GetBar(int barId)
{
// get bar using "ConnectionString" above
}
}
So my question is - Is there any benefit to ConnectionString being static? i.e. Is ConfigurationManager.ConnectionStrings["SqlConnection"].ToString(); run every time new Foo() is run thus making the static value of the property redundant as it is overwritten every time the class is initialised?
Static fields are initialized once when the first object of that class is instantiated, not every time an object is created. That makes them relatively efficient.
However, there is a downside to this, and that is that the instance-level constructors are embellished with a state machine which determines whether the one-time initialization has been completed or not.
When the first object of the class is being created, the static constructor will be invoked before any other code executes on an instance level. For subsequent instantiations, this step will be skipped, because the class has already been initialized.
This additional code, which is generated during the compilation, makes every instance-level constructor a tiny bit slower than it would otherwise be without the static members.
No, static members are initialized only once before the class is referenced for the first time in your program and it remains in memory for the lifetime of the application domain.
But in this case the field is redundant because the ConfigurationManager caches this value anyway, so doesn't read it from the configuration file everytime you access it.
I'm risking it this might be a newb question but here goes. I'm tempted to add a method to a class that could possible have thousands and thousands of instances in memory at a given time. Now, the other option is creating a static class with a static method, and just create the [static] method there, instead of an instance method in the class. Something like so:
This:
public static class PetOwner
{
public static void RenamePet(Pet pet, string newName)
{
pet.Name = newName;
}
}
Instead of this:
public class Pet
{
public string Name { get; set; }
public void Rename(string newName)
{
this.Name = newName;
}
}
I'm just wondering if the static class alternative would take considerably less memory.
Thanks!
Only data fields require storage per instance, subject to certain conditions and optimisations. For instance, 10,000 instances of a class that define an Int32 member will consume ~40,000 bytes of memory.
Strings, on the other hand, are not so simple due to interning. You can try this as an example:
object.ReferenceEquals("", string.Empty) // returns true!
If the same 10,000 instances also define a string, and that string is the same for each instance, then you're going to have 10,000 references pointing at the same data, reducing overhead considerably (but in a 32-bit environment, there's another 40,000 bytes taken up by the references).
Methods, as pointed out by others, whether static or instance, are only loaded once.
The decision to use either instance or static methods is not influenced by performance reasons, but by how the method is intended to be used. In your case, the method requires an instance of the type as its first parameter so it may as well be an instance method.
Static methods, in my experience, are most useful as an alternative to a type's constructor for returning a new instance. Constructors, once invoked, have to either return a new instance or throw an exception, which may not be desirable. Static methods can return null if something fails, or return a cached instance (the latter of which is useful if the constructor is an expensive operation).
Methods only exist once in memory, regardless if they are static or not, so there is no difference at all in memory usage.
In addition to Guffa's answer:
Methods only exist once in memory,
regardless if they are static or not,
so there is no difference at all in
memory usage.
The instance method has a class instance passed to it as an invisible(which can be explicitly accessed through this) parameter, essentially making the newName of void Rename(string newName) a second parameter passed to your instance method; thus the resulting burned instructions for static void RenamePet(Pet pet, string newName) and void Rename(string newName) look essentially the same, so they has no differences on performance or whatsoever
It doesn't make a difference, methods (static or instance) are only loaded once into memory and JIted, they don't consume more memory just because they are instance methods.
The amount of instances of a class, does not effect how much memory the method uses.
With respect to memory static and instance methods are same except the fact that instance methods can contain data members where as static methods can have only static data members.
In case of memory it doesn't make any difference,Methods exist only once in the memory regardless of being static or instance but static methods are minutely faster to invoke than instance methods because Instance methods actually use the ‘this’ instance pointer as the first parameter, so an instance method will always have that overhead
So static methods have little advantage over instance methods in case of performance but for memory usage they both use same amount.
You don't need a method "Rename" at all; you already have one, it's the setter of the Name property. Instance methods do not require more and more memory on a per instance basis, that would be silly.
Don't make design decisions like this before profiling your code. Adding an instance method to a class is not going to cause a performance bottleneck, and even if it did, you shouldn't start out with a bad design based on a guess; prove it is a bottleneck and make adjustments as necessary.
If I have a static class with a static field such as:
private static myField = new myObject();
I then have a bunch of static methods that use myField.
Is myField re-instantiated for each method call? My guess is that it's instantiated the first time a method is called that uses it and it remains in memory until the GC clears it up?
Cheers for any pointers :-)
No, it is assigned to one time, when the class is first accessed. The GC will not release the memory for this instance while the application is running - the memory will be freed when the AppDomain unloads.
There is an article by Jon Skeet about initializing and the beforefieldinit flag. It explains a bit about initializing and quotes the important parts of the C# spec, too.
It is instantitated only once. It is intantiated the moment you use a static method for the first time.
You can also instantiate it in the static construtor.
A static field initializer is run once for a given app domain, and the field remains available for the life of the program. The CG will not collect any object that is referenced by a static member variable.
If the class has a static constructor, then the static field initializer is executed just before that constructor, which occurs the first time a static member is referenced or an instance constructor is executed. If there is no static constructor, then the field is initialized at some undetermined time before any static members or instance constructors are executed.
It is assigned only once, during class initialization. That happens effectively the first time the class is "actively" touched. See: class initialization in JVM spec for exact details of when the class will be initialized.
Assuming the class this code is in is called MyClass, myField will be GCed shortly after the classloader that loaded MyClass is GCed. (classes get unloaded at classloader granularity in all the major JVMs).