Search code examples
c#sqldatareaderdatareader

Optimizing DataReader Results: what is the concequence of leaving the values as objects?


var list = new List<object[]>();
var fieldCount = reader.FieldCount;
while(reader.Read()) {
    var array = new object[fieldCount];
    reader.GetValues(array);
    list.Add(array);
}

Given the simple code snippet above. And assuming the values being retrieved are a mix of value types.

  • Is there any speed advantage if you knew the types of each column before hand, and could properly call there typed methods to get (all) their values?

  • Or is getting the typed values slowing the overall read process down?

  • What trade-offs if any are there when leaving the data in object arrays, vs storing them in a typed entity?


Solution

  • Is there any speed advantage if you knew the types of each column before hand, and could properly call there typed methods to get (all) their values?

    Yes. Because your alternative is checking for the appropriate type e.g.:

    if (obj is string)
    {
     //Do string things
    }
    else if (obj is int)
    {
     //Do int things
    }
    

    When knowing the type, simply cast:

    string t = (string) obj;
    

    Or is getting the typed values slowing the overall read process down?

    No. In fact you can´t get any faster than casting to the correct type.

    What trade-offs if any are there when leaving the data in object arrays, vs storing them in a typed entity?

    Storing them in an object array is going to use more memory, since value-types are boxed as object.