开发者

Casting/Type Conversion Performance

I have the following extension method

public static T Field<T>(this DataRow row, string columnName)
{
    return (T)Convert.ChangeType(row[columnName], typeof(T));
}

It works, but I'm trying to speed it up. Is there a way to speed that up? With a case statement and then type specific conversions? I've tried a few things like using int.Parse, but even though I know I want a开发者_C百科n int returned, I have to use ChangeType to get it to compile.

 return (T)Convert.ChangeType(intVal, typeof(T));


Do you actually need to perform a conversion, or are you just casting?

If you just need a cast then a simple return (T)row[columnName]; should do the trick.

(By the way, is using Convert.ChangeType really causing performance problems? This sounds like unnecessary micro-optimisation to me. Having said that, I'd probably prefer the plain cast for readability reasons, assuming that it meets your requirements.)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜