Reputation: 3496
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?
Upvotes: 5
Views: 170
Reputation: 11597
as we can read here classes are reference types, which means they won't be copied to the new list
you can indeed keep two lists and keep them sorted one by price
and the other by Weight
and thus make life easier for you
Upvotes: 0
Reputation: 1063433
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).
Upvotes: 7
Reputation: 151674
Will these other lists simply store
pointersreferences to the real objects and not just store them again?
As long as Item
is a class and not a struct: yes.
Upvotes: 3