【发布时间】:2017-04-10 06:41:51
【问题描述】:
我创建了一个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 的函数体中,即由于 switch(或 try-catch)而花费的时间比在 @ 中查找 Type 值要多987654324@ 并转换值(例如Convert.ToInt32)。实际上,我在函数体中花费的时间是 Dictionary.get_Item 的 3 倍...
这让我有些吃惊 - 谁能确认switch 慢得多,或者还有其他原因吗?!
更新 我删除了 try-catch 部分,但这并没有太多...
【问题讨论】:
-
我怀疑是
switch让你慢了下来。我怀疑这是需要时间的价值的拳击。如果您的字典是强类型的,那么它的工作速度会非常快。 -
switch 应该很快。这取决于。你调用这个方法多少次?不要一遍又一遍地使用 try-catch,因为那太慢了。
-
顺便说一句:(与您的性能问题无关)像
Dictionary<Type, Func<object,object>>这样的字典可以是一个更简洁的解决方案,它消除了使用 switch .... @ 987654330@ -
@L.B 感谢您的提示。
-
我想是的,因为我建议了。
标签: c# performance switch-statement