I have a class X
with large size field member y
(in terms of memory) that is declared as static member, I noticed that each time I instantiate an object of X
, this field get either loaded or reloaded in the memory. the underlying structure of y
is a dictionary<string,int>
which holds around 5000 kvs. is there a way to declare y
as a separate explicit dictionary an keep it alive during the application life time ?
Notice that: an object of X can be disposed during runtime, so the more accurate question is : if the dictionary is declared as static member of a class, would the static member remains in memory if the the class's object got garbage collected or explicitly destroyed ?
You are reinstantiating your static field in the instance constructor of the class which is causing the reload/reinstantiation of the dictionary variable. Initialize the static field either in-line where it is declared in the class
static Dictionary<string, int> y = new Dictionary<string, int>() {kvs};
OR
in a static constructor
static Dictionary<string, int> y;
static myClass()
{
y = new Dictionary<string, int>() {kvs};
}
Static constructor of a class or static field initializers run only once in their life-time.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With