Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

.net

semantics

I've generally used the KeyValuePair<TKey,TValue> type whenever I have data that is pair-related in the sense that one is a key to the other. If the data is unrelated then the Tuple<T1,T2> type makes more sense and I'd go with that.

Now I just read this article about why to generally avoid KeyValuePair<TKey,TValue> and prefer Tuple<T1,T2>. The primary argument being the performance benefit of Tuple<T1,T2>.

Outside performance, is there any reason a KVP would be a better choice than a Tuple<T1,T2>?

like image 981
Nick Gotch Avatar asked Oct 22 '13 15:10

Nick Gotch


People also ask

Is a Tuple the same as a key value pair?

Tuples are a family of types with varying number of elements and were introduced in . Net 4. Tuples support structural equality and comparison unlike KeyValuePairs. Another difference is that KeyValuePair is a struct, while Tuple types are all classes.

Is KeyValuePair immutable?

KeyValuePair is immutable - it's also a value type, so changing the value of the Value property after creating a copy wouldn't help anyway.

Are tuples mutable C#?

Tuple types are immutable. Data members of System. ValueTuple types are fields.


2 Answers

Well, the type could be considered poorly named, for one. A KeyValuePair as named should represent a key and a value. What if your two objects aren't really a key and a value, just two things? If I were to see a method or property that had a type of KeyValuePair<TKey, TValue>, I would expect the values of the KVP to be a key and a value. This is really just a matter of communicating intention and making it clear to yourself in the future, or possibly other team members. A tuple does not indicate that kind of association.

Tuples also make it easier to add another value, making it a 3-tuple (or a triplet, however you want to call it). Some .NET languages, like F#, have special syntax around tuples as well.

For an implementation perspective, Tuple does many things KeyValuePair does not. Tuples are comparable, they implement the IComparable and IStructuralEquatable interfaces, so it makes it easier to compare two tuples.

like image 152
vcsjones Avatar answered Oct 18 '22 01:10

vcsjones


KeyValuePair is struct and Tuple is a class.

That is the main difference which influences how the objects are copied whether by reference or values.

and hence Tuple<T1,T2> when passed around just uses "4byte" in 32bit OS, whereas KeyValuePair<K,V> requires more based on "K and V"

Anyhow comparing Tuple and KeyValuePair is not a good idea(doesn't makes sense for me) since both serves different purpose.

like image 24
Sriram Sakthivel Avatar answered Oct 18 '22 03:10

Sriram Sakthivel