LINQ的性能,在内存中的集合内存、性能、LINQ

2023-09-07 12:46:10 作者:溺了水的鱼

我有一个列表:收集用户有大约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);

希望帮助!