problem with tolist, is very slow

elizondo82

Member
Joined
Sep 16, 2022
Messages
12
Programming Experience
10+
Hello, my core is 3.1, when I use the tolist() is very slow the result. How can do very fast the result?
 
It's slow because you are telling your code to actually create instances for each of the objects of the IEnumerable<T>. If the object data is coming from a database across the network, and there are any kinds of filtering, sorting, or grouping that needs to happen, then all that work needs to be done right at that moment.

The questions you need to ask yourself are: "Do I really need the entire List<T> right now in memory? Or do I just process the items of the list one at a time anyway and then discard them, in which case an IEnumerable<T> is sufficient?"

Anecdote: At work a team was making our IIS server that has 48GB of RAM fall over and become completely unresponsive by loading millions and millions of rows into memory to use up over 70GB of virtual memory. And why did they need to load all those rows? Because they had a UI widget where they wanted to shows the count of items, and so they were calling IQueryable<T>().ToList().Count... because their architect said so and nobody was willing to question why.
 
How long it takes depends on what you're calling ToList on. If it's an array of 10 items and that's taking a long time then that's a problem. If it's an Entity Framework query that retrieves a million records then of course it takes some time. You haven't given us any actual information about what you're doing so we have to guess. @Skydiver has probably guessed correctly but we shouldn't have to guess at all. Show us the relevant code and provide a FULL and CLEAR explanation of the problem. You say that it's slow but it almost certainly isn't. The fact that something takes a long time does not mean that it is slow, if it has a lot of work to do. You haven't given us any indication of how much work is being done in your case.
 
Back
Top Bottom