What is the complexity of this LINQ example?

I'm curious about the overall LINQ performance. I admit this will come in handy, but how does LINQ work? I know this is a broad question. So I want to ask about a specific example:

I have an anonymous type:

var users = reader.Select(user => new MembershipUser(reader.Name, reader Age));

And now I want to convert it to MembershipUserCollection.

So, I do it like this:

MembershipUserCollection membershipUsers = new MembershipUserCollection();
users.ToList().ForEach(membershipUsers.Add); //what is the complexity of this line?

What is the complexity of the last line? Is it n ^ 2?

Does the ToList () method iterate for each user item and add it to the list? Or does ToList () work differently? Because if this is not so, I can hardly judge the reason for using the last line of code, and not just:

foreach (var user in users)
{
    membershipUsers.Add(user);
}
+3
source share
3 answers

It O (n) - .ToList() List<T> ( O (1)). , .

, , , , List<T>, ( ).

, - .ForEach() - List<T> s. , IEnumerable<T> s, -

foreach (var user in users) membershipUsers.Add(user)

; -)

+1

, ToList() , , LINQ. ToList() - , . LINQ - , LINQ . LINQ2SQL , , , .

, , , , , , . , ForEach , , , . , ( ). LINQ , , , LINQ.

, LINQ , LINQ. , . , LINQ , , LINQ. . , , , LINQ. , .

, , , LINQ , , . - , .

+2

​​ , , , , . - O (n).

The performance of using ForEach in the list compared to the foreach loop comes down to the overhead of calling a delegate and the overhead of creating and using an enumerator, I can’t say which one is faster, but if both are used in the -memory list, the complexity is the same .

0
source

Source: https://habr.com/ru/post/1771167/


All Articles