0
votes

I have an ObservableCollection in the ViewModel and I initialize it in the following way:

public ViewModel()
{
    List<T> list = null;

    using (var context = new DbContext())
    {
        list = context.Set<T>().ToList();
    }

    Items = new ObservableCollection<T>(list);
}

And every time I add an item to the context, I add it to the collection too.

public void Add<T>(T obj)
{
    using (var context = new DbContext())
    {
        context.Set<T>().Add(obj);
        context.SaveChanges();
    }

    Items.Add(obj);
}

And when to remove an item from the context, I remove it from the ObservableCollection as well.

There is yet an alternative and I can initialize the ObservableCollection again after the items are added to or removed from the context:

public void Add<T>(T obj)
{
    List<T> list = null;

    using (var context = new DbContext())
    {
        context.Set<T>().Add(obj);
        context.SaveChanges();

        list = context.Set<T>().ToList();
    }

    Items = new ObservableCollection<T>(list);
}

Now I need to know whether which way is better in case of performance and memory management?

1
Try it yourself and see. Sometimes programmers are like scientists performing interesting experiments - MickyD
Isn't it better to use others' experiences? Anyway, how may I try it? Are there any tools out there to help me with this experiment? - user3530012
Visual Studio has some pretty funky performance tools for some time now. - MickyD

1 Answers

1
votes

I would prefer the first pattern because the second reloads all items from the database. This might be the bigger performance issue than re-initializing the collection.

Further I don't see the advantage of using ObservableCollection instead of an ordinary List if you prefer to create a new instance instead of keeping the old one and handling its CollectionChange event which gets fired when adding or removing an element.