When is it better to use a Tuple versus a KeyValuePair?

前端 未结 4 1246
臣服心动
臣服心动 2021-02-01 11:49

I\'ve generally used the KeyValuePair type whenever I have data that is pair-related in the sense that one is a key to the other. If the data is

4条回答
  •  天涯浪人
    2021-02-01 12:23

    Despite the semantics, performance may be an important consideration as you consider both options. As previously mentioned, the KeyValuePair is a value type (struct), whereas the Tuple<> is a reference type (class). Therefore, the KeyValuePair is allocated on the stack and the Tuple<> is allocated on the heap, and the optimal choice is usually determined by the classic arguments of Stack vs. Heap Memory Allocation. In short, stack space is limited, but generally has very fast access. The heap memory is much larger but is somewhat slower.

    KeyValuePair may be the better choice if both the key and value types are primitives (value types like int, bool, double, etc.) or structs of small size. With primitive types on the stack, allocation and deallocation is lightning fast. This can really affect performance, especially as arguments to recursive method calls.

    On the other hand, Tuple is likely the better choice if either T1 or T2 are reference types (like classes). A KeyValuePair that contains pointers to reference types (as the key or value types) sort of defeats the purpose since the objects will need to be looked up on the heap anyway.

    Here's a benchmark I found online: Tuple vs. KeyValuePair. The only problem with this benchmark is that they tested KeyValuePair vs. Tuple, and the string type is an unusual and special type in .NET in that it can behave both like a value type and/or a reference type depending on the execution context. I believe the KeyValuePair would have been a clear winner against Tuple. Even with the deficiencies, however, the results show that the performance differences can be significant:

    8.23 ns -- Allocate Tuple
    0.32 ns -- Allocate KeyValuePair (25x faster!)

    1.93 ns -- Pass Tuple as argument
    2.57 ns -- Pass KeyValuePair as argument

    1.91 ns -- Return Tuple
    6.09 ns -- Return KeyValuePair

    2.79 ns -- Load Tuple from List
    4.18 ns -- Load KeyValuePair from List

提交回复
热议问题