Optimizing memory requirements for dictionary keys

Save that I have a (large) collection of dictionary instances. The key value in this dictionary is always one of the 10 known lines.

If the collection contains 1,000,000 records, will the value of this string key take up memory for each instance and key? Is there a good way to optimize such a case, possibly using string interning?

Another way would be to use a short word for the key and translate between the string and the short, but the syntax is a bit confused ...

+3
source share
5 answers

As others have said, it depends on how you insert the lines into your list. A couple of examples should help.

, , 1000 , . , "" 1000 :

hello
hello
hello
...

List<string> , 1000 . :

var myList = new List<string>();
var reader = new StreamReader("filename");
string s;
while ((s = reader.ReadLine()) != null)
{
    myList.Add(s);  // each string is a unique instance
}

, , , - , . . , , .

var KeyLookup = new Dictionary<string, string>();
string AddString(string key)
{
    string value;
    if (!KeyLookup.TryGetValue(key, out value))
    {
        value = key;
        KeyLookup.Add(key, value);
    }
    return value;
}

, :

while ((s = reader.ReadLine()) != null)
{
    myList.Add(AddString(s));  // duplicate strings use the same instance
}

"hello".

- . , , , , .

, , , , .

0

- . , .

. (, ), . , .

, object.ReferenceEquals().

+1

. , 4 32- . .

, .

+1

, .

,

( , )

, 10000 , , , , - .

0

( string str = "hello"; ). . , String.Intern, http://msdn.microsoft.com/en-us/library/system.string.intern.aspx. , const hello hello, . , . , , (var str2 = str1), , . , , (var str2 = ("Z" + str1).Substring(1)), you really create a new line instead of a link to the old one.

0
source

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


All Articles