How to prevent unboxing - boxing memory overhead when reading arbitrary sql rows
I'm writing a class to represent a row from a SQL query. I want the field data to be accessed via the indexer property of the class. This is straightforw开发者_如何学Goard enough if I load the data into an internal List of Object. I've already tried this and am not happy with the boxing for the primitives. Boxing increases the memory requirement by 20%. I would like to store the primitives as primitives in the class. The DataTable class stores primitives by creating arrays for each column in the schema returned from IDataReader. I implemented a class this way but I would prefer the data be stored with the row object rather than in a column that is referenced internally by the row.
Any ideas on accomplishing this?
You can generate structure type to represent a row. It can be done dynamically and it is possible to do it so there will not be any boxing. I am not sure it is worthy the effort though
Only 20% overhead? You're lucky! I just cleaned up some code where it added a fourty-fold performance decrease (not counting the impact of the extra memory)! Anyway, the typical way to prevent using object
is by starting using generics. Here's a simplified example:
class RowRepresenter<T>
{
//....
public T this[int index] {get; set;} // implementation left out
}
// initialize, suppose the properties (indexers) should be ints:
RowRepresenter<int> myInstance = new RowRepresenter<int>();
myInstance.LoadData();
// get data (i.e., your indexer)
int somefield = myInstance[2]; // no overhead, no casting required
精彩评论