SqlDataReader Performance List<string[]> or List<object[]>

余生长醉 提交于 2019-12-04 05:12:24

object only adds overhead if you are causing additional boxing. And even then, this impact is fairly minimal. In your case, reader[i] always returns object. You already have it as object, no matter whether that is a reference to a string, or an int, etc. Of course calling .ToString() adds overhead; in most cases (int, DateTime, etc) this involves both formatting code and the allocation of one (or more) extra string. By changing to string you are changing the data (for the worse, IMO - for example, you can no longer do correct sorts on dates, for example) and adding overhead. The edge case here is if all the columns are already actually strings - in which case you just add a few virtual method calls (but no extra real work).

For info, if you are after raw performance, I thoroughly recommend looking at the micro-ORMs such as dapper. They are heavily optimised, but avoid the weight of "full" ORMs. For example, in dapper:

var myData = connection.Query<TypedObject>("select * from test_table").ToList();

will, I expect, perform very comparably while giving you strongly typed object data.

Is there any reason to not use a list of object arrays instead of string arrays?

It would depend on what you wanted to do with the retrieved values after you got them into the arrays, if you're happy to treat each value as an object then having a list of objects is fine, but if you want to treat them as strings then at some point you're going to have to convert/cast the object back to a string so you're going to incur the cost somewhere.

As Cory mentioned if you're reading the value as a string from the SqlDataReader you should test using the GetString(int) method rather than calling ToString() on the value, and use this as the benchmark.

Alternatively, rather than use arrays you can read the values into a DataSet which may prove easier to work with afterwards.

End of the day, what's the best depends a lot on how you want to use the results after retrieving them from the database.

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