小编Kon*_*Rad的帖子

如何提高 C# 中 ConcurrentDictionary.Count 的性能

最近,我需要在使用SortedDictionary和之间做出选择SortedList,并选择了SortedList.

但是,现在我发现我的 C# 程序在执行 SortedList.Count 时速度变慢了,我使用调用了数千次的函数/方法进行了检查。

通常我的程序会在 35 毫秒内调用该函数 10,000 次,但是在使用 时SortedList.Count,它减慢到 300-400 毫秒,基本上慢了 10 倍。

我也尝试过SortedList.Keys.Count,但这使我的性能又降低了 10 倍,超过 3000 毫秒。

I have only ~5000 keys/objects in SortedList<DateTime, object_name>. 我可以轻松、即时地从排序列表中检索数据SortedList[date] (in 35 ms),因此我没有发现列表结构或其持有的对象有任何问题。

这种表现正常吗?

我还能用什么来获取列表中的记录数,或者只是检查列表是否已填充?(除了添加一个单独的跟踪标志,我现在可以这样做)

更正:抱歉,我实际上正在使用: ConcurrentDictionary<string, SortedList<DateTime, string>> dict_list = new ConcurrentDictionary<string, SortedList<DateTime, string>>(); 我在不同的地方有不同的计数,有时检查列表中的项目,有时检查 ConcurrentDicitonary 中的项目。所以这个问题适用于 ConcurrentDicitonary,我编写了快速测试代码来确认这一点,这需要 350 毫秒,而不使用并发。这是 ConcurrentDicitonary 的测试,显示 350 毫秒:

public static void CountTest()
{
    //Create test ConcurrentDictionary
    ConcurrentDictionary<int, string> test_dict = …
Run Code Online (Sandbox Code Playgroud)

c# performance concurrent-collections concurrentdictionary

3
推荐指数
1
解决办法
3044
查看次数