关于STRUCT优化的一个点
關于STRUCT優化的一個點
在西山居的這篇U3D cheatsheet中,提到:?c12. 確保 struct 實現了 Equals() 和 GetHashCode()
這怎么理解?
首先,看下system.object.equals和 ReferenceEquals的實現:
public static bool ReferenceEquals (object objA, object objB)
{
return objA == objB;//這就說明 了==比較的是引用
}
?
public virtual bool Equals (object obj)
{
return object.InternalEquals (this, obj);
}
?
如果是引用類型,比較時只需比較兩個引用的值(地址,指針)是否相等即可。
對于值類型的結構體,將發生由值到object的裝箱操作,生成兩個堆對象,地址分別存放在objA,objB中,objA==objB 必定不成立,因為沒有任何兩個結構體的內存地址會相同,那么它就進行InteranlEquals 的比較,這個比較是在DLL中寫的,看不到源碼,
通過對結構體進行1000000次equals測試發現,結構體中類型越多,越復雜,則equals越慢,而引用類型則不會這樣。
測試及結論如下:
class Program{#region 結構體內存分配測試struct ST{public float fx;//public string name;int ix;double[] adx;public ST(float afx, string aName){fx = afx;//name = "10"; // "hello,world, 你好嗎,!@#($)%%@$";ix = 10000000;adx = new double[ix];for(int i=0; i< ix; ++i){adx[i] = i * i;}}}class CX{public float fx;string name = "hello,world, 你好嗎,!@#($)%%@$";string name2 = "11111122334dfasdfd";string name3 = "xhello,world, dssccccc$aa$";double[] adx = new double[100];}static void testStructMem(){ST ot = new ST();ST ot2 = new ST();var st = Stopwatch.StartNew();var t1 = st.ElapsedMilliseconds;for(int i=0; i<1000000; ++i){var eq = ot.Equals(ot2);}var t2 = st.ElapsedMilliseconds;//616ms,隨著類的復雜度而上升,字符串類型,數組類型最消耗//且,一個元素的數組與10000個元素的數組幾乎沒有區別,這說明消耗在類型而不在數據長度//由此,可以判定,在進行結構體類型的比較時,是遍歷結構內的所有成員,對每個成員先判斷其類型,再進行哈希值比較//為什么要先判類型?只比較字節碼不行嗎?顯然不行,對相同的字節碼作不同類型的解釋得到的是不一樣的結果Console.WriteLine(t2 - t1); //616msvar oc = new CX();var oc2 = new CX();var st2 = Stopwatch.StartNew();st2.Start();var t11 = st2.ElapsedMilliseconds;for(int i=0; i<1000000; ++i){var eq = oc.Equals(oc2);}var t12 = st2.ElapsedMilliseconds;Console.WriteLine(t12 - t11);//5ms,與類的復雜度無關,這說明比較的是引用(地址) }#endregion?
posted on 2018-09-06 13:11 時空觀察者9號 閱讀(...) 評論(...) 編輯 收藏
總結
以上是生活随笔為你收集整理的关于STRUCT优化的一个点的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: UNITY优化资料收集
- 下一篇: Dictionary,hashtable