我知道可變結構是邪惡的。但是,我仍然想比較一個結構數組的性能與一組對象的性能。這是我到目前爲止的struct array vs object array c#
public struct HelloStruct
{
public int[] hello1;
public int[] hello2;
public int hello3;
public int hello4;
public byte[] hello5;
public byte[] hello6;
public string hello7;
public string hello8;
public string hello9;
public SomeOtherStruct[] hello10;
}
public struct SomeOtherStruct
{
public int yoyo;
public int yiggityyo;
}
public class HelloClass
{
public int[] hello1;
public int[] hello2;
public int hello3;
public int hello4;
public byte[] hello5;
public byte[] hello6;
public string hello7;
public string hello8;
public string hello9;
public SomeOtherClass[] hello10;
}
public class SomeOtherClass
{
public int yoyo;
public int yiggityyo;
}
static void compareTimesClassVsStruct()
{
HelloStruct[] a = new HelloStruct[50];
for (int i = 0; i < a.Length; i++)
{
a[i] = default(HelloStruct);
}
HelloClass[] b = new HelloClass[50];
for (int i = 0; i < b.Length; i++)
{
b[i] = new HelloClass();
}
Console.WriteLine("Starting now");
var s1 = Stopwatch.StartNew();
for (int i = 0; i < _max; i++)
{
a[i % 50].hello1 = new int[] { 1, 2, 3, 4, i % 50 };
a[i % 50].hello3 = i;
a[i % 50].hello7 = (i % 100).ToString();
}
s1.Stop();
var s2 = Stopwatch.StartNew();
for (int j = 0; j < _max; j++)
{
b[j % 50].hello1 = new int[] { 1, 2, 3, 4, j % 50 };
b[j % 50].hello3 = j;
b[j % 50].hello7 = (j % 100).ToString();
}
s2.Stop();
Console.WriteLine(((double)(s1.Elapsed.TotalSeconds)));
Console.WriteLine(((double)(s2.Elapsed.TotalSeconds)));
Console.Read();
}
這裏有一些事情我想了解。
首先,由於數組存儲結構,當我嘗試使用索引操作數組訪問一個結構,我應該得到的結構或使原有結構的引用的副本?在這種情況下,當我運行代碼後檢查數組時,我得到了變異的結構值。這是爲什麼?
其次,當我比較內CompareTimesClassVsStruct()
時序我得到大致相同的時間。這背後的原因是什麼?有沒有什麼情況下使用一個結構數組或對象數組會超越另一個呢?
感謝
MSDN有關[在類和結構之間選擇]的指導(https://msdn.microsoft.com/zh-cn/library/ms229017.aspx)。 MSDN在底部提供了方便的子彈點以加快閱讀速度。也就是說,解決結構vs類最簡單的方法是使用MSDN的指導原則,「框架中的大多數類型應該是類。」 – Brian