[英]C# get class member result caching
Does C# cache the value for a class member if the result doesn't change?如果结果不变,C# 是否会缓存类成员的值? So does C# store the value for
Area
after it is calculated and simply return it as long as X
and Y
aren't changed or does the first example calculate X * Y
for each Area
get call?那么 C# 是否在计算后存储
Area
的值,只要X
和Y
未更改,就简单地返回它,还是第一个示例为每个Area
get 调用计算X * Y
? Or in other words, are the examples below equally (from a computational view point) performant?或者换句话说,下面的例子是否同样(从计算的角度)性能?
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;
}
You can just check the IL code generated by your class.您可以只检查您的班级生成的 IL 代码。
https://sharplab.io/#v2:C4LglgNgNAJiDUAfAAgJgIwFgBQyDMABGgQMIEDeOB1RhMA9gK4BGEApgQIIBObAhgQC8APgIANAgCoCATQDcVGgAduYAG59gHBi3biKBAOZtgcggGcTZgL5CCAVgXYaBFes3amrDjIPHTFlYEtoIOTi74pAAUOt4EAB5QBLF6AJ4AlBSKLtQSofHhOdS+oamF1NY41kA=== https://sharplab.io/#v2:C4LglgNgNAJiDUAfAAgJgIwFgBQyDMABGgQMIEDeOB1RhMA9gK4BGEApgQIIBObAhgQC8APgIANAgCoCATQDcVGgAduYAG59gHBi3biKBAOZtgcggGcTZgL5CCAVgXYaBFes3amrDjIPHTFlYEtoIOTi74pAAUOt4EAB5QBLF6AJ4AlBSKLtQSofHhOdS+oamF1NY41kA===
Class:班级:
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;
}
}
Generated IL code for Area:为区域生成的 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
And as you can see - 2 getters are called and mul
multiplication call is executed.正如您所看到的 - 调用了 2 个 getter 并执行了
mul
乘法调用。
You can also take a look at JIT Asm
part at the same link.您还可以在同一链接中查看
JIT Asm
部分。 And basically no, no cache will be injected for that property, in this case it depends on the runtime.基本上不会,不会为该属性注入缓存,在这种情况下,它取决于运行时。 Runtime might apply some performance optimizations but that will not be the case.
运行时可能会应用一些性能优化,但情况并非如此。
If you convert Area to getter and assign a value to it in constructor - yes, it will require less instructions for reading.如果您将 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.