Why is the new Tuple type in .Net 4.0 a reference type (class) and not a value type (struct)

后端 未结 5 389
花落未央
花落未央 2020-12-07 18:03

Does anyone know the answer and/or have an opinion about this?

Since tuples would normally not be very large, I would assume it would make more sense to use structs

5条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-07 18:57

    If the .NET System.Tuple<...> types were defined as structs, they would not be scalable. For instance, a ternary tuple of long integers currently scales as follows:

    type Tuple3 = System.Tuple
    type Tuple33 = System.Tuple
    sizeof // Gets 4
    sizeof // Gets 4
    

    If the ternary tuple were defined as a struct, the result would be as follows (based on a test example I implemented):

    sizeof // Would get 32
    sizeof // Would get 104
    

    As tuples have built-in syntax support in F#, and they are used extremely often in this language, "struct" tuples would pose F# programmers at risk of writing inefficient programs without even being aware of it. It would happen so easily:

    let t3 = 1L, 2L, 3L
    let t33 = t3, t3, t3
    

    In my opinion, "struct" tuples would cause a high probability of creating significant inefficiencies in everyday programming. On the other hand, the currently existing "class" tuples also cause certain inefficiencies, as mentioned by @Jon. However, I think that the product of "occurrence probability" times "potential damage" would be much higher with structs than it currently is with classes. Therefore, the current implementation is the lesser evil.

    Ideally, there would be both "class" tuples and "struct" tuples, both with syntactic support in F#!

    Edit (2017-10-07)

    Struct tuples are now fully supported as follows:

    • Built into mscorlib (.NET >= 4.7) as System.ValueTuple
    • Available as NuGet for other versions
    • Syntactic support in C# >= 7
    • Syntactic support in F# >= 4.1

提交回复
热议问题