gpt4 book ai didi

c# - 是否可以在 C# 中获取对字典项的引用?

转载 作者:行者123 更新时间:2023-11-30 14:00:22 28 4
gpt4 key购买 nike

我正在对一个被调用数亿次的函数实现缓存。缓存大小为数千万项。它目前是使用 Dictionary 实现的,在其中查找需要花费大量时间。

是否有可能在 Dictionary 中获取整个对的引用,而不仅仅是值,所以我可以检查一个值是否存在,检查它(并且可能更新它)如果它确实使用了一次查找?

目前,我有这样的东西:

int val;
if (cache.TryGetValue(key, out val))
if (val < newVal) cache[key] = newVal;
else return val;
else
cache.Add(key, newVal);

我想得到这个:

Pair pair = cache.GetPair(key);
if (pair != null)
if (pair.Value < newVal) pair.Value = newVal;
else return pair.Value;
else
cache.Add(key, newVal);

如果有替代数据结构允许这样做,我也很乐意听到。

提前致谢!

最佳答案

这是受 Mare Infinitus 的回答启发。假设你的 cache变量现在是 Dictionary<string, int>你可以把它改成 Dictionary<string, MutableInt32>其中 MutableInt32是这样写的:

// wraps an int that may change
class MutableInt32
{
public int Value;
}

然后您可以将代码更改为

MutableInt32 val;
if (cache.TryGetValue(key, out val))
if (val.Value < newVal) val.Value = newVal;
else ...

关于c# - 是否可以在 C# 中获取对字典项的引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10972325/

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