Generic Arithmetic in .NET

Published July 11, 2011
Advertisement
Hrm... first post. This actually contains content from my blog, but I felt like writing it again, differently.
[hr]
It's a problem that's been tackled a hundred, billion times. My personal favourites are this and this. The first, however, I felt required too much code, and the second was too slow (disclaimer: I never tried it myself - apparently the JIT inlines the code, resulting in a very small performance difference). Then I had an idea.

Coding in IL, what if I were to force the usage of an add instruction, regardless of the input type? Ex (pseudo C#/IL here):

public static void Add(T left, T right)
{
ldarg.0
ldarg.1
add
ret
}

Testing, testing... well, what do you know, it works!! Not that I know anything about micro-benchmarking, but the performance was roughly the same as regular code (a little slower, which I assume was due to some type checking code I added).

Thus, the beginnings of a potentially awesome math (why am I getting red squiggles under this word?) library. Eventually, I produced this:

public static class Operator
where T : struct, IEquatable, IComparable
{
static Operator()
{
var type = typeof(T);
if (!type.IsPrimitive || type == typeof(bool) || type == typeof(char))
throw new ArgumentException("The specified type is not supported.", "T");
}

public static T Add(T left, T right) { return default(T); }
public static T Subtract(T left, T right) { return default(T); }

// etc
}

At post-compile time, I had a separate program rewrite the methods with the appropriate code using Mono.Cecil.

You may have noticed that I restricted the type to non-bool/char primitive types. You may also notice that the int/float/double/etc. types don't actually have any operators defined. The compiler handles them for you - that's what the add instruction is for. As such, this [s]hack [/s] trick only works on primitive types. All primitive types, and that includes bool and char. Since it's rather... impractical... to add two booleans together, I decided to filter them out too (by the way, a + b = [font="sans-serif"][size="2"]A).[/font]

[font="sans-serif"][size="2"]For those who want to get their hands on some source code, I stuck all this into a project on Codeplex. It's largely incomplete, but I'm working on it. Enjoy.[/font]

[font="sans-serif"][size="2"]YellPika[/font]
0 likes 0 comments

Comments

Nobody has left a comment. You can be the first!
You must log in to join the conversation.
Don't have a GameDev.net account? Sign up!
Profile
Author
Advertisement
Advertisement