开发者

Speeding up listbox insertion time

开发者 https://www.devze.com 2023-01-10 02:05 出处:网络
I need to add 950 strings that are 2500 characters in length to a listbox.The method I am u开发者_如何学Csing below takes 2.5 seconds and ideally it needs to happen in less then 500ms.

I need to add 950 strings that are 2500 characters in length to a listbox. The method I am u开发者_如何学Csing 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.


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.


Listbox is dealing with 2500 characters. That is what is slow. All that data, including converting to/from arrays, is peanuts in memory. Hence skipping the ToArray step not making a difference. If your users have to scroll horizontally to see this info, chances are, you're stuck with 'slow.'

If not, consider refactoring a tiny bit. Strategy: only put as many characters - about 100 - as are viewable in a regular width listbox. Full strings are retained behind the scenes.

  • Make a helper class like so (you can convert the public string to a property if you're that anal;-):
    Class TruncatedListItem
        Public Content as string
        Overrides sub ToString() as string ' Pardon me if this is wrong I always use intellisense
            return Mid(Content,1,100)
        end sub
    end class
  • Add those items to the listbox. When an item in a listbox isn't of type string, it calls the item's ToString method (which hey, we just tailored to give the listbox a break) and adds that as a string, then the items collection appears as the items you've added. (keep the begin/end update too)
    For each each itm as string in Items
        dim tli as new TruncatedListItem
        tli.Content = itm
        listbox.add(tli)
    next
  • When you want to see what the user picked, instead of getting the string like this:
    MyString = Ctype(Listbox.SelectedItem,string)  
  • do this MyString = Ctype(ListBox.SelectedItem,TruncatedListItem).Content
  • Now I am assumming the user, at some point, still needs to see all 2500 chars before selecting. Unless they are a serious stick in the mud, they should settle for this alternative (In fact there are advantages to scrolling).
    • When they double click an item, in the handler for double click, show them the full text in a messagebox. You could tell them to do that in a tooltip. For example, in the double-click handler: msgbox Ctype(ListBox.SelectedItem,TruncatedListItem).Content,,"Full Item Text"

Good luck!

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号