Interesting about a way to save memory in C # using List <> with structs

I am not even sure how I should formulate this question. I pass some CustomStruct objects as parameters to the class method and store them in a list. I am wondering if it is possible and more efficient to add multiple references to a specific instance of CustomStruct if it was found by an equivalent instance.

This is a dummy / sample structure:

public struct CustomStruct
{
    readonly int _x;
    readonly int _y;
    readonly int _w;
    readonly int _h;
    readonly Enum _e;
}

Using the following method, you can pass one, two, or three CustomStruct objects as parameters. In the final method (which takes three parameters), maybe the third and perhaps the second will have the same meaning as the first.

List<CustomStruct> _list;

public void AddBackground(CustomStruct normal)
{
    AddBackground(normal, normal, normal);
}

public void AddBackground(CustomStruct normal, CustomStruct hover)
{
    AddBackground(normal, hover, hover);
}

public void AddBackground(CustomStruct normal, CustomStruct hover, CustomStruct active)
{
    _list = new List<CustomStruct>(3);
    _list.Add(normal);
    _list.Add(hover);
    _list.Add(active);
}

, , CustomStruct, .

, , ( ) , , , </STRONG > . active.

, ? CustomStruct - ValueType, , . , . "" CustomStuct, .

CustomStruct , . , ? , CustomStruct, AddBackground (normal) , Addbackground (, , ). . Add(), , Add(), , ?

? , ?

- ?

+3
3

, . , , , , , . , , (, ).

:

_list.Add(normal); // a **copy** of normal is set into the list
_list.Add(hover); // a **copy** of hover is set into the list
_list.Add(active); // a **copy** of active is set into the list

, , () :

_list.Add(normal); // a **copy** of normal is set into the list
_list.Add(normal); // a **copy** of normal is set into the list
_list.Add(normal); // a **copy** of normal is set into the list

, (struct = stack - ). ( List<>), . struct arount Add ( , ).

+2

, , , ( 20 ).

, GC ( ).


, - , .

+1

, . Struct - , . , GC. . GC.

Your list of structures is the reference type itself, so it will be stored on the heap along with its values. Each time you add an entry to the list, the data is copied from the local view of your method to one of the slots in the list. If you save the same value several times, it will be copied several times. This is just an int list list. If you have a value of 42 ten times, you will find ten copies of the value 42 in memory for the list.

0
source

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


All Articles