First of all, carry out of the loop the check
info == "Hello word";
this is the invariant of the cycle, so you waste time on re-estimation of it. It can be optimized out, but it hurts my eyes to see such thing.
The problem I can see is hard-coded
immediate constants of the string type, never a good idea, not good for maintenance. As to performance, it could be possible that indexing
Cells
with the string is not the fastest way of addressing a cell, because, like it or not, this is some kind of the search by a key. So, try to pre-fetch the column indices of this three cells: dataGrid.Rows[i].Cells["colHelloWorld"], dataGrid.Rows[i].Cells["colBackColor"] and dataGrid.Rows[i].Cells["colForeColor"]:
http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridviewcell.columnindex.aspx[
^].
In your case, all the cells under the loop will have three different column indices, repeating in all the iterations of the cycle, which are will repeat
dataGrid.Rows.Count
times. If you pre-fetch them, you can address the cells by index in all iterations except one:
void ProcessData(string info) {
int helloWorldColumnIndex = 0;
int backColorColumnIndex = 0;
int foreColorColumnIndex = 0;
for (int i = 0; i < dataGrid.Rows.Count; ++i) {
if (i == 0) {
helloWorldColumnIndex = dataGrid.Rows[i].Cells["colHelloWorld"].ColumnIndex;
backColorColumnIndex = dataGrid.Rows[i].Cells["colBackColor"].ColumnIndex;
foreColorColumnIndex = dataGrid.Rows[i].Cells["colForeColor"].ColumnIndex;
}
var gridInfoCell = dataGrid.Rows[i].Cells[helloWorldColumnIndex];
string gridInfo = (string)gridInfoCell.Value;
if (gridInfo == info) {
gridInfoCell.Value = "Good by, and don't hard-code immediate constants anymore!";
dataGrid.Rows[i].Cells[backColorColumnIndex].Style.BackColor = Color.Red;
dataGrid.Rows[i].Cells[ForeColorColumnIndex].Style.ForeColor = Color.White;
}
}
}
Of course, this is not the best option, because you could determine the column indices in first place, when you set up the whole grid view. I only demonstrated the isolated solution, based only on your existing code and nothing else. Of course, you should not use those
immediate string constants. I hope you got the idea.
Wonderfully,
++i
instead of
i++
gives better performance. (But rename this variable to
"
index
" or something. Never use single-character identifiers.)
[EDIT #1]
The code sample is modified according to last modification of the code sample in the text of the question by OP.
[EDIT #2]
However, these improvements are just pretty much pointless rat race. The whole approach is wrong. Radically, the only real key to grid view performance is its
virtual mode. Please see:
http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.virtualmode.aspx[
^].
—SA