Immutable class vs struct

前端 未结 4 751
执念已碎
执念已碎 2021-02-03 23:55

The following are the only ways classes are different from structs in C# (please correct me if I\'m wrong):

  • Class variables are references, while struct variables
4条回答
  •  长情又很酷
    2021-02-04 00:37

    Since copying reference is cheaper than copying struct, why would one use an immutable struct?

    This isn't always true. Copying a reference is going to be 8 bytes on a 64bit OS, which is potentially larger than many structs.

    Also note that creation of the class is likely more expensive. Creating a struct is often done completely on the stack (though there are many exceptions), which is very fast. Creating a class requires creating the object handle (for the garbage collector), creating the reference on the stack, and tracking the object's lifetime. This can add GC pressure, which also has a real cost.

    That being said, creating a large immutable struct is likely not a good idea, which is part of why the Guidelines for choosing between Classes and Structures recommend always using a class if your struct will be more than 16 bytes, if it will be boxed, and other issues that make the difference smaller.

    That being said, I often base my decision more on the intended usage and meaning of the type in question. Value types should be used to refer to a single value (again, refer to guidelines), and often have a semantic meaning and expected usage different than classes. This is often just as important as the performance characteristics when making the choice between class or struct.

提交回复
热议问题