why not use linked list for stack c# #65295
-
according to https://source.dot.net/#System.Collections.NonGeneric/System/Collections/Stack.cs,6acda10c5f8b128e |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 5 replies
-
Trivial (possibly not the reason) answer - it takes less memory. For classes, a linked list takes at least twice the memory of an array (An array will contain one pointer to the data on the heap, but a linked list will need one pointer to the data, plus a pointer to the next node). Things are slightly better if the contents are structs, because the contents of the struct also occupy container memory (and so don't have pointer to the data), but it still takes some extra memory. Too, while it's true that a linked list makes it cheaper to insert/remove elements from the middle of the list, in the case of a stack this isn't necessarily helpful, because most modifications are going to happen at one end. Note too that traditional "instruction stack space" is usually laid out in sequential address space (ie, as if it were an array). |
Beta Was this translation helpful? Give feedback.
Trivial (possibly not the reason) answer - it takes less memory. For classes, a linked list takes at least twice the memory of an array (An array will contain one pointer to the data on the heap, but a linked list will need one pointer to the data, plus a pointer to the next node).
Things are slightly better if the contents are structs, because the contents of the struct also occupy container memory (and so don't have pointer to the data), but it still takes some extra memory.
Too, while it's true that a linked list makes it cheaper to insert/remove elements from the middle of the list, in the case of a stack this isn't necessarily helpful, because most modifications are going to happen a…