C # Comparison with list and list

Various attributes of Tuples and Lists;

  • Tuples are not uniform and lists are uniform,
  • Tuples are immutable, and lists are mutable,

often dictate the use of one type over another. However, in other scenarios, the data type may be equally suitable. As such, what are the implications of the memory and / or performance of Tuples compared to lists that may also influence our decision?
Thanks,

+4
source share
1 answer

Well, in addition to what you mentioned, there is a pretty significant difference in that a tuple can only contain up to eight items. (OK, you can technically make arbitrarily large tuples by making the last argument of the tuple a type of another tuple, but I can't help but feel that you need to be a little crazy to actually do this.)

Unlike tuples in a language such as Python, tuples in C # cannot really be used as general-purpose data structures. One of the most common uses of a tuple in C # is to return multiple values ​​from a function or pass multiple values ​​to functions, which for some reason can take only one (for example, when passing e.Argument to BackgroundWorker ) or any other situation in which you you cannot worry about creating a custom class, and you cannot use an anonymous type.

Since you need to know exactly how many elements (and what types of elements) they will contain at compile time, tuples are really very limited. Lists, on the other hand, are intended for storing uniform general-purpose data, where you do not always know how many items you will have. I would like to see an example of a code snippet where, as you put it, "any type of data can be equally suitable."

Furthermore, since tuples and lists solve completely different problems, there is probably a rather limited interest in comparing memory / performance effects. But for what it's worth, tuples are implemented as classes, not structures, so they are stored on the heap exactly like lists, and they are not copied when you pass them between functions, unlike value types. However, they implement the IStructuralEquatable and IStructuralComparable interfaces, and their Equals method is implemented in such a way that it returns true: new Tuple<int>(1).Equals(new Tuple<int>(1)) (meanwhile, new List<int>() { 1 }.Equals(new List<int>() { 1 }) is false).

+10
source

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


All Articles