Nei*_*ir0 -1 c# performance struct class
我构建了一个测试并获得了以下结果:
分配类:15.3260622,分配结构:14.7216018.
分配结构而不是类时看起来有4%的优势.这很酷但是真的足以添加语言值类型吗?在哪里可以找到一个显示结构真正击败类的例子?
void Main()
{
var stopWatch = new System.Diagnostics.Stopwatch();
stopWatch.Start();
for (int i = 0; i < 100000000; i++)
{
var foo = new refFoo()
{
Str = "Alex" + i
};
}
stopWatch.Stop();
stopWatch.Dump();
stopWatch.Restart();
for (int i = 0; i < 100000000; i++)
{
var foo = new valFoo()
{
Str = "Alex" + i
};
}
stopWatch.Stop();
stopWatch.Dump();
}
public struct valFoo
{
public string Str;
}
public class refFoo
{
public string Str;
}
Run Code Online (Sandbox Code Playgroud)
你的方法是错误的.您主要测量字符串分配,整数到字符串的转换以及字符串的连接.这个基准测试不值得写入.
为了看到结构的好处,比较分配1000个对象的数组和1000个结构的数组.对于数组对象,您需要为数组本身分配一个,然后为数组中的每个对象分配一个.对于结构数组,您可以为结构数组分配一个.
另外,请查看.Net集合的C#源代码中List类的Enumerator的实现.它被声明为结构.那是因为它只包含一个int,所以整个枚举器结构都适合机器字,所以它非常便宜.