This question is NOT about parsing a CSV.
Using the following code to create a CSV from a DataTable
But it is slow
100 rows by 14 columns is 4 seconds
Is there a faster way?
StringBuilder sb = new StringBuilder();
bool first = true;
int colCount = 0;
foreach (DataColumn dc in DT.Columns)
{
if (first) first = false; else sb.Append(",");
sb.Append("\"" + dc.ColumnName + "\"");
colCount++;
}
sb.AppendLine();
foreach (DataRow dr in DT.Rows)
{
first = true;
for (int i = 0; i < colCount; i++)
{
if (first) first = false; else sb.Append(",");
sb.Append("\"" + dr[i].ToString().Trim() + "\"");
}
sb.AppendLine();
}
return sb.ToString();
StringBuilder is not the problem here.
Load i from 0 to 1 million runs in 300 milliseconds
StringBuilder sb = new StringBuilder();
Stopwatch sw = new Stopwatch();
sw.Start();
for (int i = 0; i < 1000000; i++)
{
sb.Append(i.ToString());
}
sw.Stop();
Debug.Write(sw.ElapsedMilliseconds.ToString());
sb.Append("\"" + dc.ColumnName + "\"");
tosb.Append('"'); sb.Append(dc.ColumnName); db.Append('"');
. Same in your second loop. Also, single character literals may be faster than strings, where applicable. Finally (nit)first
in your second loop can be eliminated in favor of a check againsti==0
. – Lenticel