C # Performance Improvement Returning Nullable Type from SqlDataReader

I have a simple method that returns Nullable Int32 from a DataReader, and not the built-in GetInt32.

I call this method many times and have one situation where any time that I can shave would be useful.

Can anyone suggest any alternative and faster ways to get the Intable Intable value from the DataReader?

private Int32? GetNullableInt32(SqlDataReader dataReader, int fieldIndex) { return !dataReader.IsDBNull(fieldIndex) ? dataReader.GetInt32(fieldIndex) : (Int32?)null; } 
+7
performance c # nullable sqldatareader
source share
2 answers

I seem to recall that sometimes it can be faster to get the value as an object, and then check if this DBNull is not.

 private Int32? GetNullableInt32(SqlDataReader dataReader, int fieldIndex) { object value = dataReader.GetValue(fieldIndex); return value is DBNull ? (Int32?) null : (Int32) value; } 

It is at least worth a try. Please note that this assumes that you can unzip directly to int ... I don’t know exactly if this is correct, but it will be easy to see.

Now there is another approach that is somewhat less secure - it will return null for any non-integer value, even if this field is actually a string, for example:

 private Int32? GetNullableInt32(SqlDataReader dataReader, int fieldIndex) { return dataReader.GetValue(fieldIndex) as Int32?; } 

Earlier, I wrote about the β€œhow” with null-value types that were not as fast as I expected, but that might be a little different thing ... again, it's worth the time.

However, I would be very surprised if this is really a bottleneck ... of course, getting data from the database in the first place will be much more expensive. Do you have guidelines for this?

+9
source share

The code you want to optimize ( ?: Will be negligible compared to the surrounding I / O.

Thus, it will not accelerate.

+2
source share

All Articles