deveton
deveton

Reputation: 341

Should we use Tuple or ValueTuple for reference-type only variables?

There's many questions contains only difference between Tuple(class) vs ValueTuple(struct) All gone with ValueTuple where there's no GC pressure. But I don't get enough with why ValueTuple accepts all data-types then? why not just ValueTuple accepts only structs as they designed as a struct.

At a glance. Is it safe and more performance for use Reference-Types with ValueTuple?

example

ValueTuple<CarClass, EngineClass> CarBody

or shall we go

Tuple<CarClass, EngineClass> CarBody

All example I see contains ValueTuple<int, int, long, structs only> Is it designed for that purpose only? Many of code I use use ValueTuple<ReferenceTypes>

Upvotes: 4

Views: 3373

Answers (1)

Gy&#246;rgy Kőszeg
Gy&#246;rgy Kőszeg

Reputation: 18033

Why not just ValueTuple accepts only structs as they designed as a struct?

Structs always could have references. Nothing stops you from using KeyValuePair<CarClass, EngineClass> either, where KeyValuePair<TKey, TValue> is also a value type.

All gone with ValueTuple where there's no GC pressure.

There must be a misunderstanding here. Value tuples with reference type arguments will be tracked by the GC, of course. It just means there is no additional pressure because of grouping some references into a ValueTuple. On the other hand, using Tuple<> means an extra reference, which is obviously has some additional GC cost.

Is it safe for use Reference-Types with ValueTuple?

It's a bit unclear what do you mean safety here but yes, it is certainly safe.

Whether it is better than the other depends on the usage. Many parameters (ValueTuple<int, int, long, other structs>) may result in large values. If you often pass such big values around methods it may end up worse performance than just passing a reference. But if that does not matter you are totally ok with value tuples, which have a convenient syntax support (and they still can be passed by reference by the in or ref modifier if needed).

Upvotes: 7

Related Questions