gpt4 book ai didi

c# - 为什么属性(property)访问比成员(member)访问慢

转载 作者:行者123 更新时间:2023-11-30 20:34:30 24 4
gpt4 key购买 nike

我一直在尝试优化访问时间关键类的性能。当我进行测量时,我惊讶地发现成员(member)访问和属性(property)访问之间的性能存在显着差异。请参阅下面的示例:

using System;
using System.Diagnostics;

public class ClassSample {
public static int StaticField = 0;
public int InstanceMember = 0;
public int PropertyField { get; set; }
public ClassSample() {
PropertyField = 0;
}
}

public class Program {
public static void Main(string[] arg) {
var obj = new ClassSample();
int N = 10000000;
Stopwatch sp = new Stopwatch();
sp.Start();
int total = 0;
for (int i = 0; i < N; i++) {
ClassSample.StaticField = i;
total += ClassSample.StaticField;
}
sp.Stop();
Console.Out.WriteLine("Static :\t" + sp.Elapsed);
sp.Restart();

total = 0;
for (int i = 0; i < N; i++) {
obj.InstanceMember = i;
total += obj.InstanceMember;
}
sp.Stop();
Console.Out.WriteLine("Member: \t" + sp.Elapsed);
sp.Restart();

total = 0;
for (int i = 0; i < N; i++) {
obj.PropertyField = i;
total += obj.PropertyField;
}
sp.Stop();
Console.Out.WriteLine("Property:\t" + sp.Elapsed);
}
}

在我运行这个(.Net 4.5/Windows 10)的地方,我得到以下结果:

Static  :       00:00:00.0243832
Member: 00:00:00.0240386
Property: 00:00:00.0624915

所以属性访问比其他访问慢两倍多。这是预期的吗?有什么办法可以避免吗?

最佳答案

我也经历过这种情况,但后来我发现,如果正确优化 Release 目标,编译器会优化属性访问,使其在性能上与成员访问相同。尝试一下并运行 Release 目标,您应该会看到明显的改进。看起来大部分差异主要与在调试中运行有关。

关于c# - 为什么属性(property)访问比成员(member)访问慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39147508/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com