C# class vs struct
Microsoft has the following rules for using struct:
Consider defining a structure instead of a class if instances of the type are small and commonly short-lived or are commonly embedded in other objects.
Do not define a structure unless the type has all of the following characteristics:
As far as I understand, you create struct when you want a value-type behavior. Of course this gives you copying overhead when assigning and passing it to functions. But why would you follow #2 and #3? What if your value type is just too large? Moreover, I don't understand why you would ever make an immutable type to be a value type. If the type is immutable, you would better save time for passing it by reference, since anyway it cannot be changed.
The reason that I'm asking is that I'm making a game, where objects have properties like Coordinates, Velocity etc. of the type Vector2d. The question is, should I make Vector2d immutable struct (wouldn't that require tons of additional memory?), mutable struct (people say they are evil) or just class (I will have to always call vector.Clone() because otherwise I may unintentionally get two objects having same vector variable)
Moreover, I don't understand why you would ever make an immutable type to be a value type.
The int
type is an immutable type and is a perfect example of why you need immutable value types.
Imagine if int
were a reference type. It would be very expensive if you had to dereference every time you used an integer. This is in fact what happens when you use "boxed" integers (eg integers that are stored in a variable of type object
). One of the improvements in .NET compared to Java is that collections can hold unboxed integers.
If the type is immutable, you would better save time for passing it by reference
Yes if it's large and immutable then you would save time by passing it by reference. That is why the guidelines suggest that large types should be reference types.
16 bytes seems somewhat arbitrary but probably relates to the cache line size for a typical CPU. This is quite a bit smaller than a 64 byte cache line on modern CPUs. Possibly because you can't explicitly align your struct to a line.
Keeping you type immutable again avoids the need to pass by reference. Instead just return a new instance. Following references is far more costly than using cached values, keeping the object small will increase the chances of it remaining in cache.
Generally speaking, if you want reference semantics make it a class otherwise make it a struct. I would recommend you follow MS guidelines unless you can prove using a profiler (or some other empirical evidence) that there is a good reason to do otherwise.
For #2, big structures should not be easily copied, and as such should be a class most of the time. Also, these are not hard rules, just rules of thumb. If you have a good reason to not follow a rule, go ahead.
链接地址: http://www.djcxy.com/p/28062.html下一篇: C#类与结构