我需要能够对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
}
重点和要求
明确重点和要求:
当今非最佳解决方案
在上述类型上使用简单的List<T>
作为class
或struct
仍需要大约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/