Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Memory use of storing the same list twice, sorted on different criteria?

Tags:

c#

list

This is a theoretical example but hopefully it highlights my question:

Let's say I have a master list of Item objects, and an Item has two properties, say Weight and Value.

The program will very frequently be required to sort by Weight and get the lightest Item whilst elsewhere it is being sorted by Value and getting the most expensive Item.

The master list has the potential to be very large, so it would be lots of unnessary work to keep sorting the master list over and over. To save time is it possible to store the sorted result as its own list? Will these other lists simply store pointers to the real objects and not just store them again?

like image 202
MatthewMcGovern Avatar asked Aug 22 '13 10:08

MatthewMcGovern


2 Answers

This depends on whether Item is a struct or a class. If it is a class (as would be the sensible default), then both lists only contain references to the objects - there will be no duplication of all the Weight / Value values. If it is a struct, then all the values will be duplicated, as each will have a separate backing vector, and the actual structs will be in the vector. Side note: if the values are strings, then note that strings are also reference types, so the string contents won't be duplicated (unless they were created separately, without any pseudo-interning, etc).

like image 186
Marc Gravell Avatar answered Nov 14 '22 11:11

Marc Gravell


Will these other lists simply store pointers references to the real objects and not just store them again?

As long as Item is a class and not a struct: yes.

like image 45
CodeCaster Avatar answered Nov 14 '22 11:11

CodeCaster