Search code examples
c#memorygarbage

Double memory allocation in C#. Bad?


Lets say I have next class:

class MyClass
{
   public string Id {get; set;}
   public List<string> Data = new List<string>();
}

I need to fill some list of MyClass instances in next way;

// member
private List<MyClass> m_instances = new List<MyClass>();

// some function

public void MyFunc()
{
    MyClass instance = new MyClass();

    for (/* something */)
    {
        instance.Id = "id1";
        instance.Data.Add("data1");

        if (/* something */)
        {
            m_instances.Add(instance);
            instance = new MyClass(); // (!!!!)to clear data
        }
    }
}

Will GC handle it in correct way?

P.S. I could not free properties manually because there are a lot of properties...


Solution

  • It's much simpler to just move the object instantiation into the loop, at the top of the loop:

    for (/* something */)
    {
        MyClass instance = new MyClass();
        instance.Id = "id1";
        instance.Data.Add("data1");
    
        if (/* something */)
        {
            m_instances.Add(instance);
        }
    }