[英]C# get class member result caching
如果结果不变,C# 是否会缓存类成员的值? 那么 C# 是否在计算后存储Area
的值,只要X
和Y
未更改,就简单地返回它,还是第一个示例为每个Area
get 调用计算X * Y
? 或者换句话说,下面的例子是否同样(从计算的角度)性能?
public double Area => X * Y;
private double X { get; set; } = 5;
private double Y { get; set; } = 5;
public double Area { get; }
public Rectangle(double x = 5, double y = 5)
{
Area = x * y;
}
您可以只检查您的班级生成的 IL 代码。
班级:
public class C {
public double Area => X * Y;
private double X { get; set; } = 5;
private double Y { get; set; } = 5;
public C(double x, double y) {
X = x;
Y = y;
}
}
为区域生成的 IL 代码:
.method public hidebysig specialname
instance float64 get_Area () cil managed
{
// Method begins at RVA 0x2050
// Code size 14 (0xe)
.maxstack 8
IL_0000: ldarg.0
IL_0001: call instance float64 C::get_X()
IL_0006: ldarg.0
IL_0007: call instance float64 C::get_Y()
IL_000c: mul
IL_000d: ret
} // end of method C::get_Area
正如您所看到的 - 调用了 2 个 getter 并执行了mul
乘法调用。
您还可以在同一链接中查看JIT Asm
部分。 基本上不会,不会为该属性注入缓存,在这种情况下,它取决于运行时。 运行时可能会应用一些性能优化,但情况并非如此。
如果您将 Area 转换为 getter 并在构造函数中为其赋值 - 是的,它将需要更少的阅读指令。
.method public hidebysig specialname
instance float64 get_Area () cil managed
{
.custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = (
01 00 00 00
)
// Method begins at RVA 0x2050
// Code size 7 (0x7)
.maxstack 8
IL_0000: ldarg.0
IL_0001: ldfld float64 C::'<Area>k__BackingField'
IL_0006: ret
} // end of method C::get_Area
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.