zoukankan      html  css  js  c++  java
  • DataTable用数字索引和用列名索引的性能区别

    考虑几个常用的类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 框架的类库封装了许多好用的类和方法,但是由于封装得太甚,许多可能造成效率降低的代码都被封装了。而看似越好用的方法,越要小心它的效率了。

     

  • 相关阅读:
    SAP:建表时如果有QUAN、CURR类型的字段不能激活的问题
    ABAP:ALV的 Header中添加HTML内容
    iframe中cookie失效问题
    让flash自动显示代码提示的两种方式
    event.srcElement说明,方法,技巧
    ABAP:FI常用BAPI
    加入收藏夹功能(jQuery)
    ABAP笔记:BDC完整版例子
    BDC处理时用到结构BDCDATA
    ABAP 自动生成EXCEL文件并作简单格式处理
  • 原文地址:https://www.cnblogs.com/qkhh/p/2010649.html
Copyright © 2011-2022 走看看