这段.NET Framework的源代码似乎有很大的优化空间

这两天在试图解决DataGrid的一个性能问题的时候发现DataGridColumnCollection里有下面这样的一段代码。发上来跟大家一起鉴定一下有没有什么问题。

来自下面这个Method:

        /// <summary>
        ///     Sets the DisplayIndex on all newly inserted or added columns and updates the existing columns as necessary. 
        /// </summary>
        private void UpdateDisplayIndexForNewColumns(IList newColumns, int startingIndex)

代码如下(426行):

newDisplayIndex = CoerceDefaultDisplayIndex(column, columnIndex);
 
// Inserting the column in the map means that all columns with display index >= the new column's display index 
// were given a higher display index.  This is perfect, except that the column indices have changed due to the insert
// in the column collection.  We need to iterate over the column indices and increment them appropriately.  We also 
// need to give each changed column a new display index. 
InsertInDisplayIndexMap(newDisplayIndex, columnIndex);
 
for (int i = 0; i < DisplayIndexMap.Count; i++)
{
    if (i > newDisplayIndex)
    { 
        //All columns with DisplayIndex higher than the newly inserted columns
        //need to have their DisplayIndex adiusted. 
        column = ColumnFromDisplayIndex(i); 
        column.DisplayIndex++;
    } 
}

 

这两天在解决的性能问题是,DataGrid在显示Column数超过3万的数据时很慢。经过调试,发现基本上所有的时候都花在了Add Column上。糟糕的是,DataGridColumns属性是ObservableCollection<DataGridColumn>类型——没有AddRange方法。如果要添加3万个数据列,只能一次加一列地加3万次。而每次添加一个列的时候,都会运行上面的代码。其中DisplayIndexMap的作用是保存当前所有Columns的每个Column的显示顺序用的。所以有多少Columns,这个DisplayIndexMap就有多少个Item

 

大家看上面的代码有什么问题么?我个人觉得int i从0开始是在白白浪费CPU。如果是Add New Column的话,newDisplayIndex似乎多数情况下会是DisplayIndexMap.Count - 1。

posted on   南柯之石  阅读(1073)  评论(4编辑  收藏  举报

编辑推荐:
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· SQL Server 2025 AI相关能力初探
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库

导航

< 2010年11月 >
31 1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 1 2 3 4
5 6 7 8 9 10 11

统计

点击右上角即可分享
微信分享提示