Since you need to input the length of an array at the time of creation, I assume that it requires a solid, continuous block of memory. A List can be dynamically expanded, so does this mean that it does NOT require contiguous memory allocation? Would this mean it is less likely for a List to throw an "Out of Memory" Exception?
No, it is more likely to run out of memory (assuming that you are comparing creating an array of the correct size with creating a default List and adding the items to it one at a time).
A List
uses an 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 there are two copies of the data in memory during the resize, meaning more likely to run out of memory.
You can avoid this for a List
if you know the maximum size before creating the list, but in that case you could also use an array.
List<T>
is a wrapper around T[]
. That means a List<T>
does need a contiguous memory region and more memory than a T[]
. See the Answer of Matthew Watson for more details on this.
If you want to avoid OutOfMemoryExceptions, then instead of trying to cut you data structures into pieces, I suggest to run your program in 64bit mode, as it is more likely to run out of contiguous free ADDRESS SPACE rather than running out of physical RAM and SWAP nowadays. In order to run your program in x64 mode, compile it as anycpu (not prefering x86).
Raymond Chen, a programmer at Microsoft wrote a blog post about this: http://blogs.msdn.com/b/oldnewthing/archive/2013/06/28/10429807.aspx?Redirected=true#comments
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With