Why is copying 10 items to an observable collection so slow and how to speed up?

  • Thread starter Thread starter Richard.Haggard
  • Start date Start date
R

Richard.Haggard

Guest
This code operates in a .NET WPF C# environment. The basic code creates a collection of about 10 objects. The collection is sorted and then copied. When the copy happens the time to execute adds an astonishing 7 seconds. The observable collection does not have any subscribers at this point so one would not expect any time to be lost due to broadcast change notifications.

The application is based on a WinForm used to create a System Tray Notification item. When the tray icon is clicked upon a WPF window is shown. At the time that the WPF window becomes visible a DispatcherTimer is created and started. A short delay after that and a web service call is made which collects information which is written into userItems, a local variable. This collection will be passed back to the caller who will put it into a class property that will be bound to the source for a ComboBox. This code works well and fast. There is a problem with it, however, in that the contents of the ComboBox drop down list are not sorted. I thought that it would be trivial to handle that by sorting the contents of the userItems before it is passed back to the caller. Not so, sneaker breath. Here's the important part of the code:

// A local variable is declared.
ObservableCollection<UserItem> userItems = null;

// Snipped from the code is the initial population of userItems.


// A sorted copy of userItems is created. This is quick.
List<UserItem> lui = userItems.OrderBy( a => a.user_id ).ToList();


// The original collection is emptied so that it can be populated with the
// sorted elements.
userItems.Clear();


// The sorted list of items, only about 10 objects, is copied back to userItems.
// This is where the time is being spent, an astonishing 7 seconds to copy 10 items.
// If the copy is commented out then the code runs in almost no time at all.
for (int x = 0; x < lui.Count; x++)
userItems.Add( lui[x] );



Any ideas why the above code fragment runs so slowly and how can I speed it up?


Richard Lewis Haggard

Continue reading...
 
Back
Top