博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

考虑几个常用的类DataTable、GridView(Winform中的DataGridView),当要索引某个单元格的时候,需要用行或列 来定位。行定位一般是用一个整形的数字,而列定位的时候,可以使用整形的数字的索引,也可以使用string的列名来索引。这两者是有一些效率的区别的, 我们用Reflector反编译可以看出来。以DataGridView来举例:

方式1
String cellValue = gv.Rows[0].Cells[0];

方式2
String cellValue = gv.Rows[0].Cells["ColumnName"];

哪个效率会更高呢?
Cells属性的类型是DataGridViewCellCollection类型,我们反编译查看它们对于[]运行符的实现:

public DataGridViewColumn this[int index]
{
    
get
    {
        
return (DataGridViewColumn) this.items[index];
    }
}
 
public DataGridViewColumn this[string columnName]
{
    
get
    {
        
if (columnName == null)
        {
            
throw new ArgumentNullException("columnName");
        }
        
int count = this.items.Count;
        
for (int i = 0; i < count; i++)
        {
            DataGridViewColumn column 
= (DataGridViewColumn) this.items[i];
            
if (string.Equals(column.Name, columnName, StringComparison.OrdinalIgnoreCase))
            {
                
return column;
            }
        }
        
return null;
    }
}

 

可见,使用数字引用的,直接返回了内部列表对应的索引的值,而使用列名引用的,还需要遍历DataGridView的所有列,找到对应的列的索引, 再返回。这种方法造成了循环。这个循环造成的效率的降低。

如果进行大量数据绑定、或进行大量循环的时候,最好是使用列序号去索引,而不是使用列名进行索引。

在这里不得不说一下,.net 框架的类库封装了许多好用的类和方法,但是由于封装得太甚,许多可能造成效率降低的代码都被封装了。而看似越好用的方法,越要小心它的效率了。

 

posted on 2011-04-09 17:26  黑米  阅读(2288)  评论(0编辑  收藏  举报