我正在创建一个C#console-app.我有一些关键路径,并认为创建结构比创建类更快,因为我不需要对结构进行垃圾回收.在我的测试中,我发现了相反的结果.
在下面的测试中,我创建了1000个结构和1000个类.
class Program
{
static void Main(string[] args)
{
int iterations = 1000;
Stopwatch sw = new Stopwatch();
sw.Start();
List<Struct22> structures = new List<Struct22>();
for (int i = 0; i < iterations; ++i)
{
structures.Add(new Struct22());
}
sw.Stop();
Console.WriteLine($"Struct creation consumed {sw.ElapsedTicks} ticks");
Stopwatch sw2 = new Stopwatch();
sw2.Start();
List<Class33> classes = new List<Class33>();
for (int i = 0; i < iterations; ++i)
{
classes.Add(new Class33());
}
sw2.Stop();
Console.WriteLine($"Class creation consumed {sw2.ElapsedTicks} ticks");
Console.ReadLine();
}
}
Run Code Online (Sandbox Code Playgroud)
我的classe/struct很简单:
class Class33
{
public int Property { get; set; }
public int Field;
public void Method() { }
}
struct Struct22
{
public int Property { get; set; }
public int Field;
public void Method() { }
}
Run Code Online (Sandbox Code Playgroud)
结果(请滚筒......)
Struct creating consuming 3038 ticks
Class creating consuming 404 ticks
Run Code Online (Sandbox Code Playgroud)
所以问题是:为什么一个Class的时间量比结束的时间要接近10倍?
编辑.我通过将属性分配给属性来使程序"做某事".
static void Main(string[] args)
{
int iterations = 10000000;
Stopwatch sw = new Stopwatch();
sw.Start();
List<Struct22> structures = new List<Struct22>();
for (int i = 0; i < iterations; ++i)
{
Struct22 s = new Struct22()
{
Property = 2,
Field = 3
};
structures.Add(s);
}
sw.Stop();
Console.WriteLine($"Struct creating consuming {sw.ElapsedTicks} ticks");
Stopwatch sw2 = new Stopwatch();
sw2.Start();
List<Class33> classes = new List<Class33>();
for (int i = 0; i < iterations; ++i)
{
Class33 c = new Class33()
{
Property = 2,
Field = 3
};
classes.Add(c);
}
sw2.Stop();
Console.WriteLine($"Class creating consuming {sw2.ElapsedTicks} ticks");
Console.ReadLine();
}
Run Code Online (Sandbox Code Playgroud)
结果令我震惊.类仍然是至少2倍,但分配整数的简单事实有20倍的影响!
Struct creating consuming 903456 ticks
Class creating consuming 4345929 ticks
Run Code Online (Sandbox Code Playgroud)
编辑:我删除了对方法的引用,因此我的类或结构中没有引用类型:
class Class33
{
public int Property { get; set; }
public int Field;
}
struct Struct22
{
public int Property { get; set; }
public int Field;
}
Run Code Online (Sandbox Code Playgroud)
正如所评论的,决定结构与类有很多考虑因素。我没有看到很多人关心实例化,因为它通常只是基于此决定的性能影响的很小一部分。
我对您的代码进行了一些测试,发现有趣的是,随着实例数量的增加,结构速度会更快。
我无法回答你的问题,因为你的说法似乎不正确。类的实例化并不总是比结构更快。我读过的所有内容都表明相反,但你的测试产生了你提到的有趣的结果。
您可以使用一些工具来真正深入研究并尝试找出为什么会得到这样的结果。
10000
Struct creation consumed 2333 ticks
Class creation consumed 1616 ticks
100000
Struct creation consumed 5672 ticks
Class creation consumed 8459 ticks
1000000
Struct creation consumed 73462 ticks
Class creation consumed 221704 ticks
Run Code Online (Sandbox Code Playgroud)