真的 13000000 个项目是相当多的。
如果分配了 13000000 个类,那就是对垃圾收集器胃的一个非常深的打击!
另外,如果你找到一种使用默认 .NET 字典的方法,性能会非常糟糕,键太多,键的数量接近 31 位散列可以使用的值的数量,无论如何性能都会很糟糕你使用的系统,当然,内存会太多!
如果您需要一个可以使用比哈希表更多内存的数据结构,您可能需要一个自定义哈希表与自定义二叉树数据结构混合。
是的,可以编写自己的两个组合。
对于这个如此奇怪和具体的问题,你不能肯定地依赖 .net 哈希表。
考虑一棵树的查找复杂度为 O(log n),而构建复杂度为 O(n * log n),当然,构建它会太长。
然后,您应该构建一个二叉树哈希表(反之亦然),这样您就可以同时使用这两种数据结构,从而减少内存消耗。
然后,考虑在 32 位模式下编译它,而不是在 64 位模式下:64 位模式使用更多内存来存储指针。
同时,可能相反,32 位地址空间可能不足以解决您的问题。
我从来没有遇到过可以用完 32 位地址空间的问题!
如果键和值都是简单的值类型,我建议你在 C dll 中编写数据结构并通过 C# 使用它。
你可以试着写一本字典。
比方说,您可以将数据分成 26 个字典之间的 500000 个项目块,但是占用的内存会非常大,不要认为您的系统会处理它。
public class MySuperDictionary
{
private readonly Dictionary<KEY, VALUE>[] dictionaries;
public MySuperDictionary()
{
this.dictionaries = new Dictionary<KEY, VALUE>[373]; // must be a prime number.
for (int i = 0; i < dictionaries.Length; ++i)
dictionaries[i] = new Dicionary<KEY, VALUE>(13000000 / dictionaries.Length);
}
public void Add(KEY key, VALUE value)
{
int bucket = (GetSecondaryHashCode(key) & 0x7FFFFFFF) % dictionaries.Length;
dictionaries[bucket].Add(key, value);
}
public bool Remove(KEY key)
{
int bucket = (GetSecondaryHashCode(key) & 0x7FFFFFFF) % dictionaries.Length;
return dictionaries[bucket].Remove(key);
}
public bool TryGetValue(KEY key, out VALUE result)
{
int bucket = (GetSecondaryHashCode(key) & 0x7FFFFFFF) % dictionaries.Length;
return dictionaries[bucket].TryGetValue(key, out result);
}
public static int GetSecondaryHashCode(KEY key)
{
here you should return an hash code for key possibly using a different hashing algorithm than the algorithm you use in inner dictionaries
}
}