.NET 8 引入了几种旨在提高应用性能的新类型,以性能为中心的类型。
1. System.Collections.Frozen
创建集合后,这些类型就不允许对键和值进行任何更改。
此要求可实现更快的读取操作(例如,TryGetValue())。
对于在首次使用时填充,然后在长期服务期间保留的集合,这些类型特别有用。
使用Benchmark测试一亿次取值
1.先实例化四名选手分别为:Dictionary、HashSet、FrozenDictionary、FrozenSet
C#
//Dictionary
public static Dictionary<string, string> dict = new()
{
{"apple","1" },
{"orange","2" },
{"pink","3" },
{"bule","4" },
{"yellow","5" },
{"red","6" }
};
// FrozenDictionary
public static FrozenDictionary<string, string> frozendict = dict.ToFrozenDictionary();
//HashSet
public static HashSet<string> hashSetDict = dict.Keys.ToHashSet();
//FrozenSet
public static FrozenSet<string> Fset = hashSetDict.ToFrozenSet();
2. 贴上Benchmark特性,并做循环取值一亿次
C#
#region 取数据
[Benchmark]
public void Run_Dict()
{
for (int i = 0; i < 1000000000; i++)
{
dict.TryGetValue("red", out _);
}
}
[Benchmark]
public void Run_FrozDict()
{
for (int i = 0; i < 1000000000; i++)
{
frozendict.TryGetValue("red", out _);
}
}
[Benchmark]
public void Run_hashset()
{
for (int i = 0; i < 1000000000; i++)
{
hashSetDict.TryGetValue("red", out _);
}
}
[Benchmark]
public void Run_FrozSet()
{
for (int i = 0; i < 1000000000; i++)
{
Fset.TryGetValue("red", out _);
}
}
#endregion
3. 测压结果

2. SearchValues<T>
应用场景:快速查询
创建 SearchValues<T> 的实例时,将在那时派生优化后续搜索所需的所有数据,这意味着工作是预先完成的。
使用Stopwatch 测量已用时间
C#
static void Main(string[] args)
{
var sw = Stopwatch.StartNew();
var str = "adjaldashldasljhdasldadhk.[[[./'.,/09-531!@#$X";
var cstr = "X";
sw.Restart();
for (int i = 0; i < 1000000000; i++)
{
str.Contains(cstr);
}
Console.WriteLine(sw.ElapsedMilliseconds);
var svstr = SearchValues.Create("aidhawidjmsacas[d,,,[p[p@#%@!%%#@#……A"u8);
byte cbyte = (byte)"z"[0];
sw.Restart();
for (int i = 0; i < 1000000000; i++)
{
svstr.Contains(cbyte);
}
}
测试结果:显而易见得看出速度差距
