Imagine the following simple code:
public void F<T>(IList<T> values) where T : struct
{
foreach (T value in values)
{
double result;
if (TryConvertToDouble((object)value, out result))
{
ConsumeValue(result);
}
}
}
public void ConsumeValue(double value)
{
}
The problem with the above code is casting to object, which results in boxing in the loop.
Is there a way to achieve the same functionality, i.e. feeding ConsumeValue with all the values without resorting to boxing in the foreach loop? Note, that F must be a generic method.
I can live with an expensive preparation code as long as it is executed outside the loop just once. For instance, if a fancy dynamic method needs to be emitted, then it is fine if done just once.
Edit
T is guaranteed to be of some numeric type or bool.
Motivation. Imagine meta data driven application, where an agent reports a data stream, where data item type is dynamically emitted based on the data stream meta data. Imagine also, that there is normalizer engine, which knows to normalize numeric data streams according to some algorithm. The type of the incoming numeric data stream is known only at run time and can be directed to a generic method of that data type. The normalizer, however, expects doubles and produces doubles. This is just a very high level description.
Edit 2
Concerning the cast to double. Actually we have a method to convert to double with the following signature:
bool TryConvertToDouble(object value, out double result);
I should have used it in the example in the first place, but I wanted to save space and written something that is not going to work. Fixed it now.
Edit 3
The current implementation does box the values. And even if I do not have the profiler’s verdict as to performance penalty of it (if any), still I am interesting to know whether there is a solution without boxing (and without converting to string). Let me call it purely academic interest.
This really interests me, because things like that are trivial in C++ with templates, but, of course, I am not starting an argument over whether .NET generics or C++ templates are better.
Edit 4
Thanks to https://stackoverflow.com/users/267/lasse-v-karlsen who provided the answer. Actually, I have used his code sample to write a simple class like this:
public static class Utils<T>
{
private static class ToDoubleConverterHolder
{
internal static Func<T, double> Value = EmitConverter();
private static Func<T, double> EmitConverter()
{
ThrowIfNotConvertableToDouble(typeof(T));
var method = new DynamicMethod(string.Empty, typeof(double), TypeArray<T>.Value);
var il = method.GetILGenerator();
il.Emit(OpCodes.Ldarg_0);
if (typeof(T) != typeof(double))
{
il.Emit(OpCodes.Conv_R8);
}
il.Emit(OpCodes.Ret);
return (Func<T, double>)method.CreateDelegate(typeof(Func<T, double>));
}
}
public static double ConvertToDouble(T value)
{
return ToDoubleConverterHolder.Value(value);
}
}
Where:
ThrowIfNotConvertableToDouble(Type)is a simple method that makes sure the given type can be converted to double, i.e. some numeric type or bool.TypeArray<T>is a helper class to producenew[]{ typeof(T) }
The Utils<T>.ConvertToDouble method converts any numeric value to double in the most efficient way, shown by the answer to this question.
NOTE: There was a bug in my initial code for instance-based code generation. Please re-check the code below. The changed part is the order of loading values onto the stack (ie. the .Emit lines). Both the code in the answer and the repository has been fixed.
If you want to go the route of code generation, as you hint to in your question, here’s sample code:
It executes ConsumeValue (which does nothing in my example) 10 million times, on an array of ints and an array of booleans, timing the execution (it runs all the code once, to remove JIT overhead from skewing the timing.)
The output:
Roughly 65% less overhead with code generation.
The code:
Note that if you make GenerationAction, F2/3 and ConsumeValue non-static, you have to change the code slightly:
All
Action<T>declarations becomesAction<Program, T>Change the creation of the DynamicMethod to include the "this" parameter:
Change the instructions to load the right values at the right times:
Pass "this" to the action whenever it is called:
Here’s the complete changed program for non-static methods: