Saving an object in C #

I have class Xwith a member of a large field y(in terms of memory) that is declared as a static member, I noticed that every time I create an instance of the object X, this field is loaded or reloaded in memory. the underlying structure yis equal dictionary<string,int>, which contains about 5000 square meters. Is there a way to declare it yas a separate explicit dictionary, keep it for the lifetime of the application?

Note that: the X object can be deleted at runtime, so the more accurate question is: if the dictionary is declared as a static member of the class, will the static member remain in memory if the class object received garbage collection or is explicitly destroyed?

+4
source share
1 answer

You restore your static field in the constructor of the class instance, which causes the dictionary variable to reload / re-establish. Initialize the static field either in the line where it is declared in the class

static Dictionary<string, int> y = new Dictionary<string, int>() {kvs};

OR

in static constructor

static Dictionary<string, int> y;
static myClass()
{
    y = new Dictionary<string, int>() {kvs};
}

The static constructor of class initializers or static fields runs only once in their lives.

+6
source

Source: https://habr.com/ru/post/1664729/


All Articles