I have a class which is defined in the following manner. The interface and concrete type both have a Type Parameter which I expect to be a double, int, decimal or DateTime. I've added a where constraint of IComparable however this class does some heavy numeric lifting so I want to avoid boxing and unboxing. The class definitions are as follows:
public interface INumericClass<T1, T2> where T1:IComparable
where T2:IComparable
{
void DoLongNumericOperation();
}
public class NumericClass<T1, T2> : INumericClass<T1, T2> where T1:IComparable
where T2:IComparable
{
private IList _innerArray1 = new T1[1000000];
private IList _innerArray2 = new T2[1000000];
public void DoLongNumericOperation()
{
for(int i = 0; i < _innerArray1.Count; i++)
{
// some computation goes on in here
// for example, it could be
double aConstant = 123.45;
double aScalar = 56.7;
_innerArray1[i] = (Convert.ToDouble(_innerArray1[i]) * aConstant + aScalar);
_innerArray2[i] = (Convert.ToDouble(_innerArray2[i]) * aConstant + aScalar);
}
}
}
These classes would be declared and used in calling code something like as follows
var numeric = new NumericClass<int, double>();
numeric.DoLongNumericComputation();
Now internally the way I handle the multiple types is to cast T to double. However I am concerned that since I have specified that T is a type param of type IComparable that unboxing/boxing is going on. In addition DateTime provides an additional overhead. What I am doing in the case of this type is converting the .Ticks
property to a double and operating on that.
I welcome any information on what is going on under the hood in the CLR, plus suggestions to improve performance such as API changes to strongly type each of the numeric operations to improve performance and memory usage.
Edit: I should also add the above implementation is sub-optimum as if you declare NumericClass it starts throwing on the cast from Tx to double. I can only assume its casting through IComparable although Im not sure.