Lei Yang
Lei Yang

Reputation: 4335

C# performance: construct new collection with existing items using constructor or loop?

I've searched but not found answer, maybe because this question is not easy to describe. For example in WPF, I have a model Test, and a List<Test> lst, then have to construct a ObservableCollection<TestViewModel> ObsTests. There maybe 2 ways:

  1. var ObsTests = new ObservableCollection<TestViewModel>(lst
        .Select(t = > new TestViewModel(t));
    
  2. var ObsTests = new ObservableCollection<TestViewModel>();
    foreach(var test in lst)
    {
        ObsTests.Add(new TestViewModel(test));
    }
    

Please tell me which is better in performance, and tell me the best solution if AsParallel is available(such as is ObservableCollection threadsafe? I'm using .net 4.5)

Upvotes: 2

Views: 291

Answers (2)

Waldemar
Waldemar

Reputation: 5513

In case if you have standard implementation of some action, and can do the same using your code, it is better to choose the standard implementation. Also it looks more tiny :)

Upvotes: -1

pwas
pwas

Reputation: 3373

There is no difference. Ctor uses Add method from base class Collection: Reffer: click!

public ObservableCollection(List<T> list)
    : base((list != null) ? new List<T>(list.Count) : list)
{
    CopyFrom(list);
}

private void CopyFrom(IEnumerable<T> collection)
{
    IList<T> items = Items;
    if (collection != null && items != null)
    {
        using (IEnumerator<T> enumerator = collection.GetEnumerator())
        {
            while (enumerator.MoveNext())
            {
                items.Add(enumerator.Current);
            }
        }
    }
}

ObservableCollection basis on Collection so it is not thread-safe. For thread-safe collection - use some class from Concurrent namespace. More on MSDN.

You can also implement own-super-fast observable collection. Like here: Click!

Upvotes: 3

Related Questions