Completely agress with others re. go for readability and maintainability over speed. I however had a generic method which needed to get named columns passed in as parameters so it made sense to work out what there column indices were.
In the benchmarking below using column index showed a big improvement so if this is a bottleneck area or a performance critical part of your code it may be worthwhile.
The output from the code below is:
515ms with ColumnIndex
1031ms with ColumnName
static void Main(string[] args)
{
DataTable dt = GetDataTable(10000, 500);
string[] columnNames = GetColumnNames(dt);
DateTime start = DateTime.Now;
TestPerformance(dt, columnNames, true);
TimeSpan ts = DateTime.Now.Subtract(start);
Console.Write("{0}ms with ColumnIndex\r\n", ts.TotalMilliseconds);
start = DateTime.Now;
TestPerformance(dt, columnNames, false);
ts = DateTime.Now.Subtract(start);
Console.Write("{0}ms with ColumnName\r\n", ts.TotalMilliseconds);
}
private static DataTable GetDataTable(int rows, int columns)
{
DataTable dt = new DataTable();
for (int j = 0; j < columns; j++)
{
dt.Columns.Add("Column" + j.ToString(), typeof(Double));
}
Random random = new Random(DateTime.Now.Millisecond);
for (int i = 0; i < rows; i++)
{
object[] rowValues = new object[columns];
for (int j = 0; j < columns; j++)
{
rowValues[j] = random.NextDouble();
}
dt.Rows.Add(rowValues);
}
return dt;
}
private static void TestPerformance(DataTable dt, string[] columnNames, bool useIndex)
{
object obj;
DataRow row;
for (int i =0; i < dt.Rows.Count; i++)
{
row = dt.Rows[i];
for(int j = 0; j < dt.Columns.Count; j++)
{
if (useIndex)
obj = row[j];
else
obj = row[columnNames[j]];
}
}
}
private static string[] GetColumnNames(DataTable dt)
{
string[] columnNames = new string[dt.Columns.Count];
for (int j = 0; j < columnNames.Length; j++)
{
columnNames[j] = dt.Columns[j].ColumnName;
}
return columnNames;
}