0

I've got the following code

files = di.GetFiles("*.jpg");
for (int i = 0; i < files.Length; i++)
{
   il.Images.Add(System.Drawing.Image.FromFile(folder + "\\" + files[i].Name));
   lv.Items.Add(files[i].Name, i);
}

the code fills a System.Windows.Forms.ImageList with pictures from a jpg files. it also creates a System.Windows.Forms.ListView where each item is associated with a picture in the imagelist.

I made the files small and tried to optimize the code. Yet I cant get under 3 seconds for 290 ~30k jpg files(or any other format).

Do you have a better way to load the list view?

Asaf
  • 3,067
  • 11
  • 35
  • 54

2 Answers2

4

Wrap your code in BeginUpdate / EndUpdate calls for the ListView.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
2

One simple change you could make is to change this:

folder + "\\" + files[i].Name

to this:

files[i].FullName

You can also use a foreach loop instead of a for loop:

foreach (FileInfo file in files)
{
   il.Images.Add(System.Drawing.Image.FromFile(file.FullName));
   lv.Items.Add(file.Name, i);
}

And a ListView can work in either bound or unbound mode. You are using unbound mode. Sometimes it is cleaner to use bound mode.

Mark Byers
  • 811,555
  • 193
  • 1,581
  • 1,452
  • 1. I always thought that foreach is less efficient than a for loop?! Is foreach work faster? always? 2. What should I do to get a bound mode. 3. I can't tell if the files[i].FullName made it run faster but it looks much cleaner... thanks. – Asaf Aug 16 '10 at 06:16
  • After reading http://stackoverflow.com/questions/365615/in-net-which-loop-runs-faster-for-or-foreach, I think the loop is really fast with for or foreach... it's the loading image that I should optimize. – Asaf Aug 16 '10 at 06:45