在C#中,何时引用类型比值类型更有效?

blu*_*nte 2 c# performance types

有没有时间参考类型比值类型更有效?为什么?你能给我举个例子吗 ?

Ree*_*sey 10

任何时候你要在很多物体之间传递它.

每次调用带有值类型的方法,或每次调用到另一个位置时,都需要值类型成员的完整副本.如果您有相当多的成员,这可能会导致性能的巨大损失.

例如,假设您有一个具有20个int值的对象:

public class MyClass { int a; int b; int c; ... }
public class MyStruct { int a; int b; int c; ... }
Run Code Online (Sandbox Code Playgroud)

如果我们这样做:

MyClass class = new MyClass();
MyClass struct = new MyStruct();

this.CallSomeMethod(class); // Just copies one IntPtr reference!
this.CallSomeMethod(struct); // Needs to copy a large amount of data to run - 20x the other on x86, 10x on x64, since it's 20 Int32 values!
Run Code Online (Sandbox Code Playgroud)