令人惊讶的是c#开关性能不佳

时间:2016-11-25 20:55:54

标签: c# performance switch-statement

我创建了一个TypeSwitch类来使用类似于以下缩短示例的代码来投射我的字段:

static Dictionary<Type, int> TypeDefs = new Dictionary<Type, int>() 
{
    {typeof(Int16), 1},
    {typeof(Int32), 2},
    {typeof(Int64), 3},
    {typeof(IntPtr), 4},
    ...
    {typeof(String), 18}
};

public static object ConvertFromDBValue(Type type, object value) 
{
    try 
    {
        switch (TypeDefs[type]) 
        {
            case 1: // {typeof(Int16), 1},
            {
                return Convert.ToInt16(value);
            }
            case 2: // {typeof(Int32), 2},
            {
                return Convert.ToInt32(value);
            }
            case 3: // {typeof(Int64), 3},
            {
                return Convert.ToInt64(value);
            }
            ...
            ...
            ...
            case 17: // {typeof(Char), 17},
            case 18: // {typeof(String), 18},
            {
                return value.ToString().Trim();
            }
            default: 
            {
                return value;
            }
        }
    }
    catch (Exception ex) 
    {
        throw ex;
    }
}

使用检测工具,我看到超过60%的时间花在了上面的ConvertFromDBValue的函数体中,即我因为切换(或try-catch)而花费更多时间而不是查找Type值在Dictionary.get_Item中并转换价值(例如Convert.ToInt32)。实际上,我在函数体中花费的时间比Dictionary.get_Item ...

多3倍

这对我来说有点令人惊讶 - 任何人都可以确认switch这么慢,或者还有其他原因吗?!

更新 我删除了try-catch部分,但这并没有太多......

2 个答案:

答案 0 :(得分:0)

正如其他人所说,你正在支付装箱/拆箱的罚款,如果可能你应该尝试消除它。

至于方法的主体你应该摆脱字典并使用if if elses的链 - 它应该会给你一个可衡量的性能提升。

编辑

在Hogan的评论之后,我已经对它进行了测试,令我惊讶的是, dict + catch 之间的区别如果较少则介于5%之间 - 我的不完美测试中有15%(,如果略快)。

Dict+case: 987.0945ms
Ifs: 937.5104ms
Hogan's array of funcs: 854.4887ms

测试:

class Program
{
    static Dictionary<Type, int> TypeDefs = new Dictionary<Type, int>()
    {
        {typeof(Int16), 1},
        {typeof(Int32), 2},
        {typeof(Int64), 3},
        {typeof(IntPtr), 4},
        {typeof(char), 5},
        {typeof(String), 6}
    };

    static KeyValuePair<Type,object>[] _Types = new[] 
        { new KeyValuePair<Type,object> ( typeof(Int16),5 ),
        new KeyValuePair<Type,object> (typeof(Int32),57 ),
        new KeyValuePair<Type,object> (typeof(Int64),157 ),
        new KeyValuePair<Type,object> (typeof(IntPtr),new IntPtr(6) ),
        new KeyValuePair<Type,object> (typeof(String),"Hello!" ),
    };

    public static object ConvertFromDBValue(Type type, object value)
    {
        try
        {
            switch (TypeDefs[type])
            {
                case 1: // {typeof(Int16), 1},
                    {
                        return Convert.ToInt16(value);
                    }
                case 2: // {typeof(Int32), 2},
                    {
                        return Convert.ToInt32(value);
                    }
                case 3: // {typeof(Int64), 3},
                    {
                        return Convert.ToInt64(value);
                    }
                case 4: // {typeof(IntPtr), 4},
                    {
                        return value;
                    }
                case 5: // {typeof(Char), 17},
                case 6: // {typeof(String), 18},
                    {
                        return value;
                    }
                default:
                    {
                        return value;
                    }
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

    public static object ConvertFromDBValue2(Type type, object value)
    {
        try
        {
            if (type == typeof(Int16))
            {
                return Convert.ToInt16(value);
            }
            if (type == typeof(Int32))
            {
                return Convert.ToInt32(value);
            }
            if (type == typeof(Int64))
            {
                return Convert.ToInt64(value);
            }
            if (type == typeof(IntPtr))
            {
                return (IntPtr)value;
            }
            if (type == typeof(Char) || type == typeof(String))
            {
                return value.ToString().Trim();
            }
            return value;
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }


    static Func<object, object>[] funcList =
    {
        (value) => value,                    //0
        (value) => Convert.ToInt16(value),   //1
        (value) => Convert.ToInt32(value),   //2
        (value) => Convert.ToInt64(value),   //3
        (value) => value,   //4
        (value) => value,   //5
        (value) => value,   //6
        (value) => value,   //7
        (value) => value,   //8
        (value) => value,   //9
        (value) => value,   //10
        (value) => value,   //11
        (value) => value,   //12
        (value) => value,   //13
        (value) => value,   //14
        (value) => value,   //15
        (value) => value,   //16
        (value) => value,   //17
        (value) => value.ToString().Trim() //18
    };

    public static object ConvertFromDBValueHogan(Type type, object value)
    {
    return funcList[TypeDefs[type]](value);
    }

    static void Main(string[] args)
    {
        var sw = new System.Diagnostics.Stopwatch();
        Random random = new Random(113453113);


        sw.Start();
        for (int i = 0; i < 10000000; i++)
        {
            var x = random.Next(5);
            var testValue = _Types[x];
            var p = ConvertFromDBValue(testValue.Key, testValue.Value);
        }
        var elapsed = sw.Elapsed;
        Console.WriteLine($"Dict+case: {elapsed.TotalMilliseconds}ms");

        sw.Restart();
        for (int i = 0; i < 10000000; i++)
        {
            var x = random.Next(5);
            var testValue = _Types[x];
            var p2 = ConvertFromDBValue2(testValue.Key, testValue.Value);
        }
        elapsed = sw.Elapsed;
        Console.WriteLine($"Ifs: {elapsed.TotalMilliseconds}ms");

        sw.Restart();
        for (int i = 0; i < 10000000; i++)
        {
            var x = random.Next(5);
            var testValue = _Types[x];
            var p3 = ConvertFromDBValueHogan(testValue.Key, testValue.Value);
        }
        elapsed = sw.Elapsed;
        Console.WriteLine($"Hogan's array of funcs: {elapsed.TotalMilliseconds}ms");
        Console.ReadLine();
    }
}

答案 1 :(得分:-1)

这是一些示例代码,如果我的&#34;函数数组和数组索引选择&#34;不清楚。

Func<object, object>[] funcList =
   { (value) => value,                    //0
     (value) => Convert.ToInt16(value),   //1
     (value) => Convert.ToInt32(value),   //2
     (value) => Convert.ToInt64(value),   //3
     (value) => value,   //4
     (value) => value,   //5
     (value) => value,   //6
     (value) => value,   //7
     (value) => value,   //8
     (value) => value,   //9
     (value) => value,   //10
     (value) => value,   //11
     (value) => value,   //12
     (value) => value,   //13
     (value) => value,   //14
     (value) => value,   //15
     (value) => value,   //16
     (value) => value,   //17
     (value) => value.ToString().Trim() //18
   }; 

public static object ConvertFromDBValue(Type type, object value)
{
  if (TypeDefs[type] <= 18)
    return funcList[TypeDefs[type]](value);
  else
   return value;
}

如果你能保证没有大于18的值,那么为了更快地取出if (TypeDefs[type] <= 18) if语句。

  

这是未经测试的示例代码。