Wondering about a way to conserve memory in C# using List<> with structs

Posted by Michael Ryan on Stack Overflow See other posts from Stack Overflow or by Michael Ryan
Published on 2010-03-23T05:11:21Z Indexed on 2010/03/23 5:21 UTC
Read the original article Hit count: 326

Filed under:
|
|
|

I'm not even sure how I should phrase this question. I'm passing some CustomStruct objects as parameters to a class method, and storing them in a List. What I'm wondering is if it's possible and more efficient to add multiple references to a particular instance of a CustomStruct if a equivalent instance it found.

This is a dummy/example struct:

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

Using the below method, you can pass one, two, or three CustomStruct objects as parameters. In the final method (that takes three parameters), it may be the case that the 3rd and possibly the 2nd will have the same value 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);
}

As the method stands now, I believe it will create new instances of CustomStruct objects, and then adds a reference of each to the List.

It is my understanding that if I instead check for equality between normal and hover and (if equal) insert normal again in place of hover, when the method completes, hover will lose all references and eventually be garbage collected, whereas normal will have two references in the List. The same could be done for active.

That would be better, right? The CustomStruct is a ValueType, and therefore one instance would remain on the Stack, and the three List references would just point to it. The overall List size is determined not by the object Type is contains, but by its Capacity. By eliminating the "duplicate" CustomStuct objects, you allow them to be cleaned up.

When the CustomStruct objects are passed to these methods, new instances are created each time. When the structs are added to the List, is another copy made? For example, if i pass just one CustomStruct, AddBackground(normal) creates a copy of the original variable, and then passes it three times to Addbackground(normal, hover, active). In this method, three copies are made of the original copy. When the three local variables are added to the List using Add(), are additional copies created inside Add(), and does that defeat the purpose of any equality checks as previously mentioned?

Am I missing anything here?

© Stack Overflow or respective owner

Related posts about c#

Related posts about list