Foreach循环(包含LINQ)性能提高

本文关键字:性能 LINQ 循环 包含 Foreach | 更新日期: 2023-09-27 18:10:49

我希望精简以下包含foreach循环的代码,以减少迭代和/或提高性能,因为每次迭代都要创建LINQ和集合:

foreach (Contact contact in Contacts) // phone contacts, around 500-1000
{
    IEnumerable<ContactEmailAddress> emails = contact.EmailAddresses; // each has multiple emails
    foreach (Friend parseUser in parseUsers) // could be many thousands
    {
        if (emails.Where(e => e.EmailAddress == parseUser.Email).ToList().Count > 0)
        {                        
            parseUser.AddContact(contact); // function call
            verifiedUsers.Add(parseUser); // add to my new aggregated list
        }
    }
}

谢谢。

Foreach循环(包含LINQ)性能提高

与其对parseUsers中的每个项目在emails集合上进行线性搜索,不如使用可以更有效搜索的集合,例如HashSet:

foreach (Contact contact in Contacts) // phone contacts, around 500-1000
{
    HashSet<string> emails = new HashSet<string>(
        contact.EmailAddresses.Select(e => e.EmailAddress));
    foreach (Friend parseUser in parseUsers) // could be many thousands
    {
        if(emails.Contains(parseUser.Email))
        {
            parseUser.AddContact(contact); // function call
            verifiedUsers.Add(parseUser); // add to my new aggregated list
        }
    }
}

没有提高多少性能,但提高了可读性:

foreach (Friend parseUser in parseUsers) // could be many thousands
{
    var filterContacts = Contacts.Where(contact =>
                              contact.EmailAddresses.Contains(parseUser.Email));
    if (filterContact.Any())
    {
        parseUser.AddContacts(filterContacts);
        verifiedUsers.Add(parseUser);
    }
}