Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Tuple versus List Considerations

Tags:

c#

list

tuples

The different attributes of Tuples and Lists;

  • Tuples are heterogeneous and Lists are homogeneous,
  • Tuples are immutable while Lists are mutable,

often dictate the use of one type over the other. In other scenarios, however, either data type could be equally appropriate. As such , what are the memory and/or performance implications of Tuples versus Lists that might also guide our decision?
Thanks,

like image 440
Seymour Avatar asked Sep 03 '13 11:09

Seymour


1 Answers

Well, in addition to what you've mentioned there's the rather significant difference that a tuple can only contain up to eight items. (OK, you can technically make arbitrarily large tuples by making the last tuple argument type another tuple, but I can't help but feel that you'd have to be slightly insane to actually do that.)

Unlike tuples in a language like Python, tuples in C# can't really be used as a general purpose data structure. One of the most common use cases for a tuple in C# is for returning multiple values from a function, or passing multiple values to functions that for some reasons can only take one (e.g. when passing e.Argument to a BackgroundWorker), or any other situation where you can't be bothered to make a custom class, and you can't use an anonymous type.

Since you need to know exactly how many items (and what types of items) they will contain at compile time, tuples are really of severely limited use. Lists, on the other hand, are for general purpose storage of homogeneous data, where you don't necessarily know how many items you're going to have. I'd love to see an example of a piece of code where, as you put it, "either data type could be equally appropriate".

Furthermore, since tuples and lists solve completely different problems, it's probably of fairly limited interest to compare the memory/performance implications. But for what it's worth, tuples are implemented as classes, not as structs, so they're stored on the heap just like lists, and they aren't copied when you pass them between functions, unlike value types. They do however implement the IStructuralEquatable and IStructuralComparable interfaces, and their Equals method is implemented such that this will return true: new Tuple<int>(1).Equals(new Tuple<int>(1)) (meanwhile, new List<int>() { 1 }.Equals(new List<int>() { 1 }) is false).

like image 122
Magnus Grindal Bakken Avatar answered Sep 21 '22 15:09

Magnus Grindal Bakken