性能優化之二:結構體類型的性能優化

C#裏結構體是值類型,其局部變量的空間分配在棧上。不少同窗喜歡用它,是由於它的存儲密度高、分配和回收成本很是低。html

可是前幾天在查熱點的時候,卻碰到結構體的性能很是慢,甚至遠低於把一樣數據結構作成的引用類型。下文對這個問題作了些簡化,方便你們理解。性能優化

代碼分析

優化前的源代碼示例:數據結構

//結構體聲明
    public struct Point2D
    {
        public int X { get; set; }
        public int Y { get; set; }   
    }

var target = new Point2D() { X = 99, Y = 100 };
//熱點語句,points 是一個有幾百萬元素的鏈表:
foreach(var item in point2Ds)
{
    if (item.Equals(target))
        return target;
}

優化方法很簡單,就是在Point2D的結構體聲明中,加一個手寫的Equals方法:ide

//優化後:
    public struct Point2D
    {
        public int X { get; set; }
        public int Y { get; set; }

        public bool Equals(Point2D obj)
        {
            return obj.X == this.X && obj.Y == this.Y;
        }
    }

性能測試

構造一個有1千萬元素的points。微服務

優化前的執行時間(單位:ms)性能

優化後的執行時間(單位:ms)測試

 先後提高差很少50%。優化

原理分析

查看IL能夠發現,優化後是調用的Point2D.Equals方法,也就是咱們寫的方法:this

 而優化前的IL以下,是調用Object.Equals方法:spa

那麼,這二者有什麼區別呢?

能夠查看一下struct的Equals方法。因爲struct是值類型,它從ValueType繼承來,所以Equals方法實際是執行的ValueType.Equals。

源碼地址:https://referencesource.microsoft.com/mscorlib/system/valuetype.cs.html

public abstract class ValueType {
 
        [System.Security.SecuritySafeCritical]
        public override bool Equals (Object obj) {
            BCLDebug.Perf(false, "ValueType::Equals is not fast.  "+this.GetType().FullName+" should override Equals(Object)");
            if (null==obj) {
                return false;
            }
            RuntimeType thisType = (RuntimeType)this.GetType();
            RuntimeType thatType = (RuntimeType)obj.GetType();
 
            if (thatType!=thisType) {
                return false;
            }
 
            Object thisObj = (Object)this;
            Object thisResult, thatResult;
 
            // if there are no GC references in this object we can avoid reflection 
            // and do a fast memcmp
            if (CanCompareBits(this))
                return FastEqualsCheck(thisObj, obj);
 
            FieldInfo[] thisFields = thisType.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
 
            for (int i=0; i<thisFields.Length; i++) {
                thisResult = ((RtFieldInfo)thisFields[i]).UnsafeGetValue(thisObj);
                thatResult = ((RtFieldInfo)thisFields[i]).UnsafeGetValue(obj);
                
                if (thisResult == null) {
                    if (thatResult != null)
                        return false;
                }
                else
                if (!thisResult.Equals(thatResult)) {
                    return false;
                }
            }
 
            return true;
        }
    }

能夠發現,ValueType.Equals方法並非直接比較的二者引用地址是否相等,而是遞歸遍歷struct的每一個字段,判斷它們是否相等。而在遍歷struct字段時,使用了反射取值,這是很耗性能的。

另外,因爲其參數是Object類型,會把傳入的struct作一次裝箱,這也是熱點。

而咱們寫的方法,是直接對比屬性,並且傳入參數是Point2D類型,也不用裝箱,能夠直接使用。

 

總結一下,在使用結構體的時候,避免裝箱,重寫Equals方法避免原Equals的反射。

 

性能優化相關文章:

微服務下,接口性能優化的一些總結

相關文章
相關標籤/搜索