views:

162

answers:

3

Hi

I'm using ADO.NET to communicate some db, and searching for a way to avoid boxing when setting the DbParameter.Value property to value-type.

Is there a way to avoid boxing in DbParameter.Value?

Thanks.

+2  A: 

I don't think so. If you examine the Value property of the SqlParameter class in Reflector, you will see that the internal field where the value is stored is also of type object. There is no place for it to store ints or floats or whatever any other way.

Ray
+4  A: 

Why do you want to avoid it? The performance cost of boxing is probably next to nothing in the context of the overall data access layer. Serializing the parameter value on the wire alone is probably 100 times the cost of boxing. Are you seeing a performance problem attributable to boxing?

Josh Einstein
The problem is not with the boxing itself, the problem is with the GC that need to collect all those boxed versions later. The process that runs it consumes 100% CPU, so i want to optimize all those little things that can cause GC to work longer.
DxCK
I don't think the 100% CPU usage is caused to the GC. The GC doesn't run permanently, it runs when it needs to...
Thomas Levesque
A: 

You can't avoid using boxed values, but you can avoid the actual boxing. Or rather, you can change how and when the boxing occurs.

You can prepare boxed values to use in parameters, for example:

object[] boxedIntegers = new object[100];
for (int i = 0; i < boxedIntegers.Length; i++) {
   boxedIntegers[i] = i;
}

As long as you keep the array, the boxed values can be used over and over without causing any more boxing, and they will not be collected until the array goes out of use.

It's doubtful that boxing is really causing any performance problems, but now you have a way to do some real testing at least.

Guffa