共计 1294 个字符,预计需要花费 4 分钟才能阅读完成。
导读 | 最近在解决性能优化的问题,看到了一堆嵌套循环,四五层级的循环真的有点过分了,在数据量成万,十万级别的时候,真的非常影响性能。本文介绍了 C# 减少嵌套循环的两种方法,帮助各位选择适合自己的优化方案,优化程序性能 |
当然,除了关注明显的循环例如 for、foreach,还应该关注隐晦一点的循环,例如 datatable.select(),linq 之类的 list.where、list.find 等。
要优化,排除业务问题,要考虑的就是代码技术了。看到循环查找数据,尽可能向 Dictionary 靠拢。
eg1:一个简单的 key 对应一条 datarow
优化前:
using System.Linq; | |
namespace ConsoleApp1 | |
{ | |
internal class Program | |
{private static void Main(string[] args) | |
{DataTable table = new DataTable(); | |
... | |
for (int i = 0; i r["num"].ToString() == i.ToString()); | |
... | |
} | |
} | |
} | |
} |
优化后:
using System.Data; | |
using System.Linq; | |
namespace ConsoleApp1 | |
{ | |
internal class Program | |
{private static void Main(string[] args) | |
{DataTable table = new DataTable(); | |
... | |
var dict = table.AsEnumerable().ToDictionary(r => r["num"].ToString()); | |
for (int i = 0; i | |
eg2:一个拼装的 Key 对应多条 DataRow 的字典 | |
优化前: | |
using System.Data; | |
using System.Linq; | |
namespace ConsoleApp1 | |
{ | |
internal class Program | |
{private static void Main(string[] args) | |
{DataTable table = new DataTable(); | |
... | |
for (int i = 0; i r["num"].ToString() == i.ToString() && r["name"].ToString() == name); | |
} | |
} | |
} | |
} | |
优化后: | |
using System.Data; | |
using System.Linq; | |
namespace ConsoleApp1 | |
{ | |
internal class Program | |
{private static void Main(string[] args) | |
{DataTable table = new DataTable(); | |
var group = table.AsEnumerable().GroupBy(r => GetGroupKey(r["num"].ToString(), r["name"].ToString())); | |
var dict= group.ToDictionary(r=>r.Key); | |
... | |
for (int i = 0; i | |
量变会引起质变。 | |
阿里云 2 核 2G 服务器 3M 带宽 61 元 1 年,有高配 | |
腾讯云新客低至 82 元 / 年,老客户 99 元 / 年 | |
代金券:在阿里云专用满减优惠券 | |
正文完
星哥玩云-微信公众号
