C# Performance gain returning a Nullable Type from a SqlDataReader

ぐ巨炮叔叔 提交于 2019-11-30 20:10:01

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?

The code you want to optimize (the ?:) will be insignificant compared to the surrounding I/O.

So, it's not going to get any faster.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!