最新下载
热门教程
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
C# 从 List<T> 移除空元素的优化例子
时间:2022-06-25 07:59:47 编辑:袖梨 来源:一聚教程网
代码评审中偶尔会发现一些通用的性能问题,在此作记录分享。
需求
我们有时候需要延迟删除 List
优化前
static void RemoveNull
for (int i = list.Count - 1; i >= 0; i--)
if (list[i] == null)
list.RemoveAt(i); // O(n)
}
由于 RemoveAt() 是 时间的操作,整个函数是 。但这个问题只需要 时间。
优化后
只要把第一个空元素之后的非空元素往前移,就能实现。
static void RemoveNull
// 找出第一个空元素 O(n)
int count = list.Count;
for (int i = 0; i < count; i++)
if (list[i] == null) {
// 记录当前位置
int newCount = i++;
// 对每个非空元素,复制至当前位置 O(n)
for (; i < count; i++)
if (list[i] != null)
list[newCount++] = list[i];
// 移除多余的元素 O(n)
list.RemoveRange(newCount, count - newCount);
break;
}
}
List
C++ 可用 std::remove, std::remove_if,因为支持内联不需考虑调用成本。
相关文章
- 最终幻想14水晶世界水栖蝾螈打法指南 07-03
- 崩坏星穹铁道哀丽秘榭全战利品位置汇总 07-03
- 崩坏星穹铁道3.3虫鸣秘闻解谜指南 07-03
- 宗门志金丹期玩法攻略 07-03
- ps怎么给照片中的人物画眉? ps眉毛修图的教程 07-03
- 区块链:新设备登录欧意app账户,如何验证?新设备登录账户验证教学 07-03