views:

75

answers:

2

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;
}
+6  A: 

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?

Jon Skeet
I do have benchmarks for this, and yes, this is by no means the slowest part of the call, however, I have done all I can in getting the data back faster and now just looking to shave the last couple of seconds off. I am running tests against these two methods now and will post the results.
Robin Day
+1 doubtful its the bottleneck also - very rarely does network or I/O out-perform a CPU.
Adam
On profiling for 5 million calls on each method.My method runs in 998msYour first method runs in 1169msYour second method runs in 898msThat's a 10% gain and good enough for me! Thanks!
Robin Day
+2  A: 

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.

Henk Holterman
+1 indeed, sounds like a micro-optimization at best, the OP also mentions in the comments that it runs 5 million times in 2 seconds... sounds fast enough to me.
Adam