Good, fast, pretty code: How to choose?

time to read 3 min | 506 words

I have a piece of code that does something on types. It is a whole complex thing that does a lot of stuff. And the code is really ugly, here is a small part from ~180 lines method.

image

The problem would have been much simpler if we could only switch on types, which is effectively what I want to do here. As it stands, however, the JIT is actually going to replace all those if statements with pointer comparisons to the method table, so this is pretty fast. Unpleasant to read, but really fast.

I decided to see what it would take to create a more readable version:

public class TypeCounter
{
    public int Long;

    public Dictionary<Type, Action<object>> Actions;

    public TypeCounter()
    {
        Actions = new Dictionary<Type, Action<object>>
        {
            [typeof(long)] = o => Long++,
            [typeof(int)] = o => Long++,
        };
    }
    public void Dic(object instance)
    {
        if (instance == null)
            return;
        Action<object> value;
        if (Actions.TryGetValue(instance.GetType(), out value))
            value(instance);

    }
    public void Explicit(object instance)
    {
        if (instance is int)
            Long++;
        else if (instance is long)
            Long++;
    }
}

This is just a simpler case of the code above, focused on just the two options. The dictionary version is much more readable, especially once you get to more than a couple of types. The problem, I have tested this on both this two types option as well as 10 types, and in all cases, the explicit version is about twice as fast.

So this rules it out, and we are left with the sad looking code that can run.