LINQ的性能,在内存中的集合 [英] Linq performance for in-memory collection

查看:412
本文介绍了LINQ的性能,在内存中的集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个列表:收集用户有大约100K +记录用户(从数据库满载像生物领域,名字的所有用户对象,姓氏等)。这个系列是从数据库中读取在应用程序启动并保存在内存中。

I have a list: Collection users which has around 100K+ records of users (all user objects fully loaded from the database with fields like Bio, First name, last name etc). This collection is fetched on application start from the database and is kept in memory.

然后,我有code这样的:

Then I have code like:

User cachedUser = users.FirstOrDefault(x => string.Equals(x.UserName, username,
StringComparison.CurrentCultureIgnoreCase));

我用从该集合获取用户。但不知何故,我注意到,这个操作是非常缓慢的。有没有同时使用LINQ的大型对象的内存集合查询性能问题?如果我想获得一个用户的每一次我改为调用数据库?

Which I use to fetch users from this collection. But somehow I noticed that this operation is incredibly slow. Is there a performance issue while using Linq to query in memory collection of large objects? Should I instead call the DB each time I want to get a user?

推荐答案

如果你想优化你的反应时间,你可以创建一个词典< T,U> 和搜索用户中:

If you want to optimize your response time and you could create a Dictionary<T,U> and search the user within:

    Dictionary<string, User> usersDictionary = new <Dictionary<string, User>(StringComparer.CurrentCultureIgnoreCase);

    // After querying the users from the DB add them to the dictionary             
    usersDictionary.Add(user.UserName, user);

    // Then when you need to retrieve a user
    User retrieveUser = null; 
    usersDictionary.TryGetValue(username, out retrieveUser);

希望帮助!

这篇关于LINQ的性能,在内存中的集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆