Click to See Complete Forum and Search --> : Optimize this code


d00_ape
February 6th, 2009, 01:38 AM
I have a function that very often are called. Any tip on how to optimize this code:

private static double CalculateDifferance(object from, object to)
{
if (typeof(int) == from.GetType())
{
return (int)to - (int)from;
}
else if (typeof(DateTime) == from.GetType())
{
return ((DateTime)to - (DateTime)from).TotalSeconds;
}
else if(typeof(double) == from.GetType())
{
return (double)to - (double)from;
}
return double.NaN;
}

jmedved
February 6th, 2009, 01:44 AM
Quick idea - make overloaded function for each type instead of checking type and casting.

RaleTheBlade
February 7th, 2009, 12:47 PM
Or you could use generics and a custom interface and have the method instill a generic constraint such as:


public static T CalculateDifference<T>(T numOne, T numTwo) where T : ISubtractable
{
// Perform subtractions here
}


And have ISubtractable overload the "-" operator.
But then you end up needing to build a wrapper class for your numerical values and implement the ISubtractable interface... so I guess its not all that "elegant" in the end.

toraj58
February 9th, 2009, 10:17 AM
in general from the aspect of OOP programming when you use many typeof and casting in your function is the symptom that you need to use polymorphism.

BTW in your case you don't need optimize you need re-design. you may understand what will be happen in your method when you pass Object to it but assume that you work in a team and you provide interface to another programmer how do you expect he understand your function prototype intuitively.

it would be better that you do the hard job yourself and make job of others easy. so overload the function for each type or use Generics

in other hand it seems that your function is not needed at all.
for those types that intrinsically support subtracting there is no need to your function and for those that do not support you can use operator overloading that is more elegant than having such function you have wrote.