Totally aggression with other people. go for readability and maintainability in speed. However, I had a general method that required to get named columns passed as parameters, so it makes sense to figure out what the column indexes were.
There was a significant improvement in the comparative analysis below using the column index, so if this is a narrow area or a critical part of your code, this might be useful.
The output from the code below:
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; }
Charlie openshaw
source share