I have a C# program that is pulling in a .csv file that is approx. 42,000 lines long. All data in the file is stored as follows:
Zipcode,City,State
I am pulling all the information into three different columns in a listview
.
Currently this data takes about 30 - 50 seconds to be brought into my program. My question is how can I better optimize my code to get this time down?
The following is a snippet of my code. The commented code is code I previously tried, but had no success in reducing the time, therefore I rewrote it in a way that was easier to read.
//These are globally declared.
lvZip.Columns.Add("Zipcode", 150, HorizontalAlignment.Left);
lvZip.Columns.Add("City", 150, HorizontalAlignment.Left);
lvZip.Columns.Add("State", 150, HorizontalAlignment.Left);
lvZip.View = View.Details;
lvZip.Items.Clear();
//string dir = System.IO.Path.GetDirectoryName(
// System.Reflection.Assembly.GetExecutingAssembly().Location);
//string path = dir + @"\zip_code_database_edited.csv";
//var open = new StreamReader(File.OpenRead(path));
//foreach (String s in File.ReadAllLines(path))
//{
// Zipinfo = s.Split(',');
// Zipinfo[0] = Zipinfo[0].Trim();
// Zipinfo[1] = Zipinfo[1].Trim();
// Zipinfo[2] = Zipinfo[2].Trim();
// lvItem = new ListViewItem(Zipinfo);
// lvZip.Items.Add(lvItem);
//}
//open.Close();
StreamReader myreader = File.OpenText(path);
aLine = myreader.ReadLine();
while (aLine != null)
{
Zipinfo = aLine.Split(',');
Zipinfo[0] = Zipinfo[0].Trim();
Zipinfo[1] = Zipinfo[1].Trim();
Zipinfo[2] = Zipinfo[2].Trim();
lvItem = new ListViewItem(Zipinfo);
lvZip.Items.Add(lvItem);
aLine = myreader.ReadLine();
}
myreader.Close();
BeginUpdate()
andEndUpdate()
will give the more visible performance boost. But theAddRange()
approach suggested by Tweety will add further optimization to your code. And although the performance boost might be less notable likeAddRange()
- theTextFieldParser
class was made specially to handle structured text files like CSV.