C# Tuple versus List Considerations

流过昼夜 提交于 2021-02-18 12:36:06

问题


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,


回答1:


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).



来源:https://stackoverflow.com/questions/18591253/c-sharp-tuple-versus-list-considerations

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!