c# - Adding to List<t> becomes very slow over time -


i'm parsing html table has 1000 rows. i'm adding ~10 char string 1 <td> in each row list<string> object. it's quick first 200 or loops becomes slower , slower on time.

this code i'm using:

list<string> mylist = new list<string>();         int maxrows = numrows;           (int = 1; < maxrows; i++)         {              tablerow newtable = mytable.tablerows[i];             string coll = string.format("{0},{1},{2},{3},{4}",newtable.tablecells[0].text,newtable.tablecells[1].text,newtable.tablecells[2].text,newtable.tablecells[3].text,newtable.tablecells[4].text);             mylist.add(coll);             label1.text = i.tostring();         } 

should use array instead?

edit: threw above code in new method gets run on new thread , updated label control code:

label1.invoke((methodinvoker)delegate                 {                     label1.text = i.tostring();                 }); 

program runs @ consistent speed , doesn't block ui.

if know range (number of items) in collection better use array.

reason : every time add element list if list full allocates new block of memory hold double current space , copies there , keeps appending additional entries till becomes full, , 1 more allocation copy cycle.

following how works afaik, start 16 elements default, when add 17th element list allocates 32 elemnts , copies 16 there continues 17 32. , repeats process, slower offer flexibility of not having determine length beforehand. might reason you're seeing drag.

thanks @dyppl var list = new list<int>(1000); 1 elegant option too, @dyppl suggested best of both worlds.


Comments

Popular posts from this blog

c# - How to set Z index when using WPF DrawingContext? -

razor - Is this a bug in WebMatrix PageData? -

visual c++ - Using relative values in array sorting ( asm ) -