C# Performance gain returning a Nullable Type from

2019-02-13 13:19发布

问题:

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;
}

回答1:

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?



回答2:

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.