C#:通过内存有效搜索200万个对象,而无需外部依赖

标签 c# performance optimization memory-management in-memory

我需要能够对C#中约200万个项目的集合进行搜索。搜索应该可以在多个字段中进行。简单的字符串匹配就足够了。

使用之类的外部依赖关系数据库不是选项,但是使用内存数据库是可以的。

主要目标是这样做节省内存的

集合中的类型非常简单,没有长字符串:

public class Item
{
    public string Name { get; set; } // Around 50 chars
    public string Category { get; set; } // Around 20 chars
    public bool IsActive { get; set; }
    public DateTimeOffset CreatedAt { get; set; }
    public IReadOnlyList<string> Tags { get; set; } // 2-3 items
}

重点和要求

明确重点和要求:
  • 没有外部依赖项(如数据库)
  • 内存高效(200万个项目低于2 GB)
  • 集合中的可搜索项(必须是高性能的)

  • 当今非最佳解决方案

    在上述类型上使用简单的List<T>作为classstruct仍需要大约2 GB的内存。

    有更好的方法吗?

    最佳答案

    在您的类(class)中,最重要的内存消耗是使用只读列表。摆脱它,您将减少大约60%的内存占用(通过三个标签进行测试):

    public class Item
    {
        public string Name { get; set; }
        public string Category { get; set; }
        public bool IsActive { get; set; }
        public DateTimeOffset CreatedAt { get; set; }
        public string Tags { get; set; } // Semi-colon separated
    }
    

    另外,请考虑使用DateTime而不是DateTimeOffset。这将进一步减少约10%的内存空间。

    关于C#:通过内存有效搜索200万个对象,而无需外部依赖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62326068/

    相关文章:

    algorithm - 查找最小函数

    c++ - 使用内联函数是否与直接在代码中编写函数体一样快?

    python - "ValueError: Unknown optimizer: momentum"动量优化器的正确名称?

    java - SHA 256 从 Java 到 C#

    c# - Windows 上的 Kestrel 和 macOS/Linux 上的 Kestrel 之间的日期反序列化差异

    multithreading - 戈朗 : why using goroutines to parallelize calls ends up being slower?

    mysql - 获取 news_tags 和 users_tags 的交集查询速度慢

    c# - 什么是一些好的 .NET 分析器?

    c# - 写入现有的 XML 文件

    wcf - 为什么我的客户发送请求如此缓慢?