gpt4 book ai didi

c# - 没有字典的快速多键查找?

转载 作者:太空宇宙 更新时间:2023-11-03 21:53:02 26 4
gpt4 key购买 nike

我有一个 Id 映射缓存,它占用了太多内存。它用于容纳一个对象的 3 种不同类型的 Id 的组合,它们的映射从表中读取,并缓存在 6 个不同的字典中,以便从任何 1 种 Id 类型快速查找/转换为另一种(性能是对我的申请很重要)。

我想将其重写为占用内存更小的内容,因此我实现了一个统一的 ID 列表,并使用 linq/lambda 表达式提取我想要的值。目前看起来像这样。

public struct IdMappings
{
public int Id1;
public int Id2;
public int Id3;
}

//new cache
private static List<IdMappings> AllIdMappings = null;

//current cache implementation
private static Dictionary<int, int> Id1ToId2 = null;
private static Dictionary<int, int> Id1ToId3 = null;
//etc.

public static void FillCache(DataSet data)
{
foreach (DataRow r in data.Tables[0].Rows)
{
//fill list and/or dictionaries with id's
}
}

示例查找将是:

public static int GetId2FromId1(int id1)
{
return AllIdMappings.FirstOrDefault(m => m.Id1 == id1).Id2;
//or
return Id1ToId2[id1];
}

这在减少内存使用方面满足了我的需要,但查找性能因此受到影响,因此我正在了解如何实现不同的东西。有没有一种方法可以比遍历列表更快地执行多索引键或多键查找?

最佳答案

如果添加这三个词典:

private static Dictionary<int, IdMappings> Id1Lookup = null;
private static Dictionary<int, IdMappings> Id2Lookup = null;
private static Dictionary<int, IdMappings> Id3Lookup = null;

如果字典值是相同的引用,它应该使用最少的内存,但保持与原始实现相同的查找速度。

如果我考虑的是正确的,这应该使用您的 6 字典解决方案的一半内存,但两倍 List<IdMappings>键入解决方案。

正如@SWeko 指出的那样,IdMappings需要是 class不是struct以确保使用引用指针而不是它的副本。

关于c# - 没有字典的快速多键查找?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13593375/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com