views:

30

answers:

2

I need to add 950 strings that are 2500 characters in length to a listbox. The method I am using below takes 2.5 seconds and ideally it needs to happen in less then 500ms.

Stopwatch sw = Stopwatch.StartNew();

listBox1.BeginUpdate();
listBox1.Items.AddRange(items.ToArray());
listBox1.EndUpdate();

sw.Stop();

What would be the best way to optimize the insertion time?

Thanks.

+1  A: 

One thing you could try is changing this line:

listBox1.Items.AddRange(items.ToArray());

to something like this:

foreach (var item in items)
{
    listBox1.Items.Add(item);
}

That way, you do not have the overhead of creating a whole new array (the ToArray() call) before putting the items into your ListBox.

Zach Johnson
Thanks for the suggestion. Unfortunately, that takes the same amount of time as the addrange method.
Eric
@Eric: Hmm...ok. Do you happen to have Visual Studio 2010 and its profiler or have access to another profiler that could tell you where the most time is being spent in those lines?
Zach Johnson
Using the profiler included with vs2010 it appears that all the time is being spent in the `Add` or `AddRange` methods.
Eric
+1  A: 
FastAl
I'm not at a Pc with .net on it so apologies if it doesn't actually speed things up. But I can't see how it won't. Thumb your nose at me if I'm wrong!!
FastAl