Answer the question
In order to leave comments, you need to log in
Why is it that what is considered an advantage of classes over structs is sometimes presented as a disadvantage?
I wondered why tuples in C# decided to implement based on ValueTuple (struct) and not based on Tuple (class), found this on stackoverflow:
https://stackoverflow.com/questions/41084411/whats...
there is the main answer:
When the .NET language design team decided to incorporate tuples and add syntax sugar to them at the language level an important factor was performance. With ValueTuple being a value type, you can avoid GC pressure when using them because (as an implementation detail) they'll be allocated on the stack.
As mentioned, I propose to make tuple types structs rather than classes, so that no allocation penalty is associated with them. They should be as lightweight as possible.
Arguably, structs can end up being more costly, because assignment copies a bigger value. So if they are assigned a lot more than they are created, then structs would be a bad choice.
. So the common pattern would be to construct, return and immediately deconstruct them. In this situation, structs are clearly preferable.
// res - это структура
var res = (sum: 0, count: 0);
return res ;
// res - это класс
var res = new {sum = 0, count = 0};
return res ;
Answer the question
In order to leave comments, you need to log in
Let's think logically. For the structure, you need to write data to the stack, copy and return, remove the stack. For the class, you need to allocate space in memory, write a reference to the data on the stack, copy and return the reference, remove the stack, and then also strain the garbage collector.
Question: which is easier? Copy data or copy link + do lots of memory manipulation and garbage collection? Of course, when the size of the link is comparable to the size of the data (just the case of tuples), then it's easier to do all this through the stack, performing an order of magnitude fewer operations. Well, when the size of the data is much larger than the link itself, then, obviously, classes should be used.
ps Pure logic without any deepening into programming and .Net.
when the size of the link is comparable to the size of the data (just the case of tuples)
struct VeryBigStructure{
// тут сотни жирных полей-структур
VeryBigStructure one;
...
VeryBigStructure oneHundred;
public static (VeryBigStructure fitst, VeryBigStructure second) GetTwoVeryBigDataObjects()
{
var res = (first: new VeryBigStructure(), second: new VeryBigStructure());
return res;
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question