【发布时间】:2018-07-08 02:08:33
【问题描述】:
我已经实现了一个非常简单的查找缓存,以优化某些数据库实体的处理。缓存类如下所示:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SyncEngine.Caches
{
class TenantsCache : Cache
{
System.Collections.Generic.List<tenant> list;
public override void ReadFromDB()
{
using (var ctx = new MyContext())
{
this.list = ctx.tenants.ToList<tenant>();
}
}
public override void Add(object o)
{
list.Add((tenant)o);
}
public tenant LookupByFNandGID(string fn, int groupId)
{
tenant match = null;
foreach (tenant t in list)
{
if (t.friendlyName == fn && t.groupId == groupId) // <-- slowest line
{
match = t;
break;
}
}
return match;
}
}
}
通过分析 CPU 使用率,我发现这个 Lookup(特别是高亮行)占用了最多的处理时间。
是否有更好、更有效的方法来实现此查找/缓存和/或此处的比较?有没有更高效的内置集合,通过两个字段进行优化查找?
【问题讨论】:
-
如果你想在数据库级别解决这个问题(你应该),分布式数据库就是你正在寻找的机器人。在性能重要的情况下或与主数据库的连接不可靠的情况下(移动应用程序),许多进程内数据库可以充当本地缓存数据库。对于 SQL,它将是 SQL Express。但是,当您对速度提出质疑时,我觉得有必要将速度咆哮联系起来:ericlippert.com/2012/12/17/performance-rant Particulary Parts 2 and 4 mater for your case.
-
谢谢,但是是的,我真的需要回答这个问题,我不知道差异是否相关,直到我有一些东西可以比较。
标签: c# performance entity-framework caching