C#的性能增益,从一个SqlDataReader返回一个空类型 [英] C# Performance gain returning a Nullable Type from a SqlDataReader
问题描述
我有一个从DataReader返回一个空Int32,而不是建在GetInt32等的简单方法。
我调用这个方法很多很多次,并有一种情况在那里任何时候我可以剃掉,这将是有益的。
任何人都可以提出任何替代方案,并得到一个空Int32出的DataReader的更快的方式?
私人的Int32? GetNullableInt32(SqlDataReader的DataReader的,诠释字段索引)
{
的回报!dataReader.IsDBNull(字段索引)?
dataReader.GetInt32(字段索引):(?Int32)已空;
}
我的显得的回顾,它有时可以更快地获得价值作为对象,然后检查,如果这是为DBNull。
私人INT32? GetNullableInt32(SqlDataReader的DataReader的,INT字段索引)
{
对象值= dataReader.GetValue(字段索引);
返回值是DBNull的? (?Int32)已空(Int32)已值;
}
它至少值得一试。请注意,这是假设你可以直接拆箱到 INT
...我不知道自己是否这是正确的,但它会很容易看到的。
现在还有另一种方法是少了几分安全的 - 它会返回null任何非整数值,即使字段实际上是一个字符串,例如:
私人的Int32? GetNullableInt32(SqlDataReader的DataReader的,INT字段索引)
{
返回dataReader.GetValue(字段索引)如的Int32 ?;
}
我以前写的关于为与不是快速可空类型如我所料,但这可能是一个稍微不同的情况下...再次,这是值得拥有的一展身手。
不过,我会,如果这真的很奇怪是真正的瓶颈......肯定获得在首位的数据库中的数据将是昂贵得多。你有基准呢?
I have a simple method that returns a Nullable Int32 from a DataReader rather than the built in GetInt32.
I am calling this method many many times and have one situation where any time I can shave off of it would be beneficial.
Can anyone suggest any alternative and faster ways of getting a nullable Int32 out of the DataReader?
private Int32? GetNullableInt32(SqlDataReader dataReader, int fieldIndex)
{
return !dataReader.IsDBNull(fieldIndex) ?
dataReader.GetInt32(fieldIndex) : (Int32?)null;
}
I seem to recall that it can sometimes by faster to get the value as an object and then check if that's DBNull.
private Int32? GetNullableInt32(SqlDataReader dataReader, int fieldIndex)
{
object value = dataReader.GetValue(fieldIndex);
return value is DBNull ? (Int32?) null : (Int32) value;
}
It's at least worth a try. Note that this is assuming you can unbox straight to an int
... I don't know for sure whether that's correct, but it'll be easy to see.
Now there's another approach which is somewhat less safe - it will return null for any non-integer value, even if the field is actually a string, for example:
private Int32? GetNullableInt32(SqlDataReader dataReader, int fieldIndex)
{
return dataReader.GetValue(fieldIndex) as Int32?;
}
I've previously written about "as" with nullable types not being as fast as I'd expect, but this may be a slightly different case... again, it's worth having a go.
However, I'd be really surprised if this is genuinely a bottleneck... surely getting the data from the database in the first place is going to be far more expensive. Do you have benchmarks for this?
这篇关于C#的性能增益,从一个SqlDataReader返回一个空类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!