What is the maximum number of items I can put inside a List<T> in C#?

Asked

Viewed 1,028 times

9

I have several questions of performance in my application. What is the maximum number of items I can within my List<T> and what is "acceptable" within good practice.

  • https://stackoverflow.com/questions/2009217/whats-the-max-items-in-a-listt

  • The limit is on the mustache’s response. Now, on best practices: in general when you want to improve performance the first point to attack is the complexity of the algorithms you use, not the size of your structures. If the problem is an inadequate algorithm, then you can think about changing the structure to use another algorithm.

1 answer

10


Since the type of the access index to the object of List is a int (.NET Core) the theoretical limit is 2 raised to 31 or 2,147,483,648.

But this is more complicated than it looks. In general each object can only have 2GB of total size allocated. So the amount of items you may actually have depends on the type T. The larger it is, the less items it can allocate. Remembering that if T is a type by reference its size is always 4 or 8 bytes depending on the architecture.

There is one more detail. In 64 bits it is possible to connect the ability to increase the size of the object with the framework <gcAllowVeryLargeObjects> (available in 4.5 forward, and of course in Core), there in thesis it is possible to work with all the items that the index supports. I just think it will be practical with small objects or reference, and preferably if you have a lot of RAM.

If you need more items than 2 billion need a different structure, you can even use the List as a reference and change the index to a long which becomes virtually impossible to burst.

Remember that anything that makes virtual memory act to keep switching pages from RAM to secondary storage like HDD or SSD can make the application into performance tragedy. And since this good practice business is soft talk, there’s no telling when you crossed the line like that. You have to measure, you have to analyze, simulate, you have to specify where your application can run well and let the person accept the degradation if you run with less RAM than you specified.

  • you know some tool or command for me to know how much memory(RAM) X object is using?

  • 1

    @Leonardobonetti is not so simple, in code you can only know approximate (https://answall.com/q/199618/101). You have filling tools: https://answall.com/q/108239/101.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.