Arrays versus lists for memory problems

Since you need to enter the length of the array at creation time, I assume that this requires a continuous, continuous block of memory. The list can be dynamically expanded, does this mean that it does NOT require contiguous memory allocation? Does this mean that it is less likely that List will move the exception "from memory"?

+4
source share
3 answers

No, most likely you will run out of memory (provided that you compare the creation of an array of the correct size with the creation of a default list and adding elements to it one at a time).

A List uses the array internally, and when it needs to resize it, it creates a new array twice the size of the original and copies the original into it, and then frees the original array.

This means that during resizing, there are two copies of the data in memory, which means that out of memory is likely to end.

You can avoid this for List if you know the maximum size before creating the list, but in this case you can also use an array.

+7
source

List<T> - a wrapper around T[] . This means that List<T> requires a region of adjacent regions and more memory than T[] . See Matthew Watson's Answer for more details on this.

If you want to avoid OutOfMemoryExceptions, instead of trying to cut data structures into pieces, I suggest running your program in 64-bit mode, since it will likely exhaust the adjacent free space ADDRESS, rather than exhaust physical RAM and SWAP at the moment. To run your program in x64 mode, compile it as anycpu (not preferring x86).

Raymond Chen, a Microsoft programmer, wrote a blog post about this: http://blogs.msdn.com/b/oldnewthing/archive/2013/06/28/10429807.aspx?Redirected=true#comments

+1
source

In C # List , an array is supported, not a linked list. This is similar to vector in C ++. A list that does not require a continuous block of memory is LinkedList . However, be careful, as it is known to be slower and more error prone.

See Starcraft developer articles (good self reading): http://www.codeofhonor.com/blog/avoiding-game-crashes-related-to-linked-lists

0
source

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


All Articles