Performance Byte[] to Generic I'm in need to make a byte[] -> T extension method and need it to be fast (no need for it being pretty)

This function will be called 100's of 1000's of times in very short succession in an absolute performance critical environment.

We're currently optimizing on "ticks" level, every tick translates to a couple milliseconds higher in the callstack, thus the need of raw speed over maintainability (not how I like to design software, but the reasoning behind this is out of scope).

Consider the following code, it's clean and maintainable, but it's relatively slow (probably due to boxing and unboxing), Can this be optimized to be faster?

public static T ConvertTo&lt;T&gt;(this byte[] bytes, int offset = 0)
{
    var type = typeof(T);
    if (type == typeof(sbyte)) return bytes[offset].As&lt;T&gt;();
    if (type == typeof(byte)) return bytes[offset].As&lt;T&gt;();
    if (type == typeof(short)) return BitConverter.ToInt16(bytes, offset).As&lt;T&gt;();
    if (type == typeof(ushort)) return BitConverter.ToUInt32(bytes, offset).As&lt;T&gt;();
    if (type == typeof(int)) return BitConverter.ToInt32(bytes, offset).As&lt;T&gt;();
    if (type == typeof(uint)) return BitConverter.ToUInt32(bytes, offset).As&lt;T&gt;();
    if (type == typeof(long)) return BitConverter.ToInt64(bytes, offset).As&lt;T&gt;();
    if (type == typeof(ulong)) return BitConverter.ToUInt64(bytes, offset).As&lt;T&gt;();

    throw new NotImplementedException();
}

public static T As&lt;T&gt;(this object o)
{
    return (T)o;
}


And yes it needs to be generic, sadly
First, you seem to have a minor typo on this line:

if (type == typeof(ushort)) return BitConverter.ToUInt32(bytes, offset).As&lt;T&gt;();


That should be:

if (type == typeof(ushort)) return BitConverter.ToUInt16(bytes, offset).As&lt;T&gt;();


Just as well, you have a bug in here that is a pretty big one (causes exception on any attempts to convert anything to sbyte with your method):

if (type == typeof(sbyte)) return bytes[offset].As&lt;T&gt;();


Should be:

if (type == typeof(sbyte)) return ((sbyte)bytes[offset]).As&lt;T&gt;();




If you really need speed, you should probably not use the BitConverter class in this situation. Use bitwise operators, as they are much faster.

See this answer for a comparison.

You should also not use .As&lt;T&gt; either, and instead cast within the method using: (T)(object). This eliminates unnecessary stack overhead.

Two improvements we can make immediately:


Replace all the BitConverter work with bitwise work.
Replace all the .As&lt;T&gt;() with (T)(object) casts instead.




Performance Evaluation

The performance difference, when those changes are made is significant for certain types of T.

ConvertTo1&lt;byte&gt; on 50000000 rounds, time (in ms) taken: 3465
ConvertTo1&lt;short&gt; on 50000000 rounds, time (in ms) taken: 4217
ConvertTo1&lt;int&gt; on 50000000 rounds, time (in ms) taken: 5586
ConvertTo1&lt;long&gt; on 50000000 rounds, time (in ms) taken: 7665
ConvertTo2&lt;byte&gt; on 50000000 rounds, time (in ms) taken: 4995
ConvertTo2&lt;short&gt; on 50000000 rounds, time (in ms) taken: 5775
ConvertTo2&lt;int&gt; on 50000000 rounds, time (in ms) taken: 6945
ConvertTo2&lt;long&gt; on 50000000 rounds, time (in ms) taken: 8492
ConvertToInt on 50000000 rounds, time (in ms) taken: 1092

Verifying results of conversions are same:
SByte test: 1, 1: True
Byte test: 1, 1: True
Short test: 10497, 10497: True
UShort test: 10497, 10497: True
Int test: 755378433, 755378433: True
UInt test: 755378433, 755378433: True
Long test: 4041804345027995905, 4041804345027995905: True
ULong test: 4041804345027995905, 4041804345027995905: True


Now, to explain, ConvertTo1&lt;T&gt; is the optimized method, ConvertTo2&lt;T&gt; is the original, and ConvertToInt is a strongly-typed method for converting directly to int.

By removing .As&lt;T&gt;() and replacing with (T)(object), and replacing all the BitConverter work with bitwise work, we cut our work down to:


69% original time for byte
73% original time for short
80% original time for int
90% original time for long


Also note that we returned the exact same values for all situations.



Just how bad is performance dragging because of the boxing?

Badly. If we consider another method, ConvertTo3 which is strongly typed around an int parameter, we can come up with the following result:

ConvertToInt on 50000000 rounds, time (in ms) taken: 1034


Now that is with a method that only returns an int value.

This leads us to be able to conclude that, due to the boxing of the generic types, and recasting them, we lose a lot of performance. (Around 500% or so right-off-the-bat.) The issues isn't the fact that you use generics, the issue is that you use boxing several times within, which creates extra overhead.



Using an .As&lt;T&gt;() method

While it would make sense to think that this would be fairly quick, with no drawbacks, this is actually much slower than inline calls due to the overhead of having an additional method call. Replacing .As&lt;T&gt;() with (T)(object) right out of the gate gave us significant performance back. It may even be acceptable to only make that change and continue using BitConverter.

In fact, upon further research, it seems that if you replace the ConvertTo2 method I supplied with this variant:

    public static T ConvertTo2&lt;T&gt;(this byte[] bytes, int offset = 0)
    {
        var type = typeof(T);
        if (type == typeof(sbyte)) return (T)(object)((sbyte)bytes[offset]);
        if (type == typeof(byte)) return (T)(object)bytes[offset];
        if (type == typeof(short)) return (T)(object)BitConverter.ToInt16(bytes, offset);
        if (type == typeof(ushort)) return (T)(object)BitConverter.ToUInt16(bytes, offset);
        if (type == typeof(int)) return (T)(object)BitConverter.ToInt32(bytes, offset);
        if (type == typeof(uint)) return (T)(object)BitConverter.ToUInt32(bytes, offset);
        if (type == typeof(long)) return (T)(object)BitConverter.ToInt64(bytes, offset);
        if (type == typeof(ulong)) return (T)(object)BitConverter.ToUInt64(bytes, offset);

        throw new NotImplementedException();
    }


The performance difference between ConvertTo1 and ConvertTo2 is very minimal. (Though, removing the BitConverter work still does seem to make it slightly faster, the difference is very insignificant at this level.)

Food for thought.



Code

Here's the code I used for conversions:

public static class Extensions
{
    public static T ConvertTo1&lt;T&gt;(this byte[] bytes, int offset = 0)
    {
        var type = typeof(T);
        if (type == typeof(sbyte)) return (T)(object)((sbyte)bytes[offset]);
        if (type == typeof(byte)) return (T)(object)bytes[offset];
        if (type == typeof(short)) return (T)(object)((short)(bytes[offset + 1] &lt;&lt; 8 | bytes[offset]));
        if (type == typeof(ushort)) return (T)(object)((ushort)(bytes[offset + 1] &lt;&lt; 8 | bytes[offset]));
        if (type == typeof(int)) return (T)(object)(bytes[offset + 3] &lt;&lt; 24 | bytes[offset + 2] &lt;&lt; 16 | bytes[offset + 1] &lt;&lt; 8 | bytes[offset]);
        if (type == typeof(uint)) return (T)(object)((uint)bytes[offset + 3] &lt;&lt; 24 | (uint)bytes[offset + 2] &lt;&lt; 16 | (uint)bytes[offset + 1] &lt;&lt; 8 | bytes[offset]);
        if (type == typeof(long)) return (T)(object)((long)bytes[offset + 7] &lt;&lt; 56 | (long)bytes[offset + 6] &lt;&lt; 48 | (long)bytes[offset + 5] &lt;&lt; 40 | (long)bytes[offset + 4] &lt;&lt; 32 | (long)bytes[offset + 3] &lt;&lt; 24 | (long)bytes[offset + 2] &lt;&lt; 16 | (long)bytes[offset + 1] &lt;&lt; 8 | bytes[offset]);
        if (type == typeof(ulong)) return (T)(object)((ulong)bytes[offset + 7] &lt;&lt; 56 | (ulong)bytes[offset + 6] &lt;&lt; 48 | (ulong)bytes[offset + 5] &lt;&lt; 40 | (ulong)bytes[offset + 4] &lt;&lt; 32 | (ulong)bytes[offset + 3] &lt;&lt; 24 | (ulong)bytes[offset + 2] &lt;&lt; 16 | (ulong)bytes[offset + 1] &lt;&lt; 8 | bytes[offset]);

        throw new NotImplementedException();
    }

    public static T ConvertTo2&lt;T&gt;(this byte[] bytes, int offset = 0)
    {
        var type = typeof(T);
        if (type == typeof(sbyte)) return ((sbyte)bytes[offset]).As&lt;T&gt;();
        if (type == typeof(byte)) return bytes[offset].As&lt;T&gt;();
        if (type == typeof(short)) return BitConverter.ToInt16(bytes, offset).As&lt;T&gt;();
        if (type == typeof(ushort)) return BitConverter.ToUInt16(bytes, offset).As&lt;T&gt;();
        if (type == typeof(int)) return BitConverter.ToInt32(bytes, offset).As&lt;T&gt;();
        if (type == typeof(uint)) return BitConverter.ToUInt32(bytes, offset).As&lt;T&gt;();
        if (type == typeof(long)) return BitConverter.ToInt64(bytes, offset).As&lt;T&gt;();
        if (type == typeof(ulong)) return BitConverter.ToUInt64(bytes, offset).As&lt;T&gt;();

        throw new NotImplementedException();
    }

    public static int ConvertToInt(this byte[] bytes, int offset = 0)
    {
        return (bytes[offset + 3] &lt;&lt; 24 | bytes[offset + 2] &lt;&lt; 16 | bytes[offset + 1] &lt;&lt; 8 | bytes[offset]);
    }

    public static T As&lt;T&gt;(this object o)
    {
        return (T)o;
    }
}


And the test code:

public class CR_101636
{
    public static void _Main(string[] args)
    {
        var rounds = 50000000;
        var bytes = new byte[] { 1, 41, 6, 45, 163, 95, 23, 56 };

        Stopwatch sw = new Stopwatch();
        sw.Start();
        for (int i = 0; i &lt; rounds; i++)
        {
            byte result = bytes.ConvertTo1&lt;byte&gt;(0);
        }
        sw.Stop();
        Console.WriteLine("ConvertTo1&lt;byte&gt; on {0} rounds, time (in ms) taken: {1}", rounds, sw.ElapsedMilliseconds);
        sw.Reset();

        sw.Start();
        for (int i = 0; i &lt; rounds; i++)
        {
            short result = bytes.ConvertTo1&lt;short&gt;(0);
        }
        sw.Stop();
        Console.WriteLine("ConvertTo1&lt;short&gt; on {0} rounds, time (in ms) taken: {1}", rounds, sw.ElapsedMilliseconds);
        sw.Reset();

        sw.Start();
        for (int i = 0; i &lt; rounds; i++)
        {
            int result = bytes.ConvertTo1&lt;int&gt;(0);
        }
        sw.Stop();
        Console.WriteLine("ConvertTo1&lt;int&gt; on {0} rounds, time (in ms) taken: {1}", rounds, sw.ElapsedMilliseconds);
        sw.Reset();

        sw.Start();
        for (int i = 0; i &lt; rounds; i++)
        {
            long result = bytes.ConvertTo1&lt;long&gt;(0);
        }
        sw.Stop();
        Console.WriteLine("ConvertTo1&lt;long&gt; on {0} rounds, time (in ms) taken: {1}", rounds, sw.ElapsedMilliseconds);
        sw.Reset();

        sw.Start();
        for (int i = 0; i &lt; rounds; i++)
        {
            byte result = bytes.ConvertTo2&lt;byte&gt;(0);
        }
        sw.Stop();
        Console.WriteLine("ConvertTo2&lt;byte&gt; on {0} rounds, time (in ms) taken: {1}", rounds, sw.ElapsedMilliseconds);
        sw.Reset();

        sw.Start();
        for (int i = 0; i &lt; rounds; i++)
        {
            short result = bytes.ConvertTo2&lt;short&gt;(0);
        }
        sw.Stop();
        Console.WriteLine("ConvertTo2&lt;short&gt; on {0} rounds, time (in ms) taken: {1}", rounds, sw.ElapsedMilliseconds);
        sw.Reset();

        sw.Start();
        for (int i = 0; i &lt; rounds; i++)
        {
            int result = bytes.ConvertTo2&lt;int&gt;(0);
        }
        sw.Stop();
        Console.WriteLine("ConvertTo2&lt;int&gt; on {0} rounds, time (in ms) taken: {1}", rounds, sw.ElapsedMilliseconds);
        sw.Reset();

        sw.Start();
        for (int i = 0; i &lt; rounds; i++)
        {
            long result = bytes.ConvertTo2&lt;long&gt;(0);
        }
        sw.Stop();
        Console.WriteLine("ConvertTo2&lt;long&gt; on {0} rounds, time (in ms) taken: {1}", rounds, sw.ElapsedMilliseconds);
        sw.Reset();

        sw.Start();
        for (int i = 0; i &lt; rounds; i++)
        {
            int result = bytes.ConvertToInt(0);
        }
        sw.Stop();
        Console.WriteLine("ConvertToInt on {0} rounds, time (in ms) taken: {1}", rounds, sw.ElapsedMilliseconds);
        sw.Reset();

        Console.WriteLine("");
        Console.WriteLine("Verifying results of conversions are same:");

        Console.WriteLine("SByte test: {0}, {1}: {2}", bytes.ConvertTo1&lt;sbyte&gt;(), bytes.ConvertTo2&lt;sbyte&gt;(), bytes.ConvertTo1&lt;sbyte&gt;() == bytes.ConvertTo2&lt;sbyte&gt;());
        Console.WriteLine("Byte test: {0}, {1}: {2}", bytes.ConvertTo1&lt;byte&gt;(), bytes.ConvertTo2&lt;byte&gt;(), bytes.ConvertTo1&lt;byte&gt;() == bytes.ConvertTo2&lt;byte&gt;());
        Console.WriteLine("Short test: {0}, {1}: {2}", bytes.ConvertTo1&lt;short&gt;(), bytes.ConvertTo2&lt;short&gt;(), bytes.ConvertTo1&lt;short&gt;() == bytes.ConvertTo2&lt;short&gt;());
        Console.WriteLine("UShort test: {0}, {1}: {2}", bytes.ConvertTo1&lt;ushort&gt;(), bytes.ConvertTo2&lt;ushort&gt;(), bytes.ConvertTo1&lt;ushort&gt;() == bytes.ConvertTo2&lt;ushort&gt;());
        Console.WriteLine("Int test: {0}, {1}: {2}", bytes.ConvertTo1&lt;int&gt;(), bytes.ConvertTo2&lt;int&gt;(), bytes.ConvertTo1&lt;int&gt;() == bytes.ConvertTo2&lt;int&gt;());
        Console.WriteLine("UInt test: {0}, {1}: {2}", bytes.ConvertTo1&lt;uint&gt;(), bytes.ConvertTo2&lt;uint&gt;(), bytes.ConvertTo1&lt;uint&gt;() == bytes.ConvertTo2&lt;uint&gt;());
        Console.WriteLine("Long test: {0}, {1}: {2}", bytes.ConvertTo1&lt;long&gt;(), bytes.ConvertTo2&lt;long&gt;(), bytes.ConvertTo1&lt;long&gt;() == bytes.ConvertTo2&lt;long&gt;());
        Console.WriteLine("ULong test: {0}, {1}: {2}", bytes.ConvertTo1&lt;ulong&gt;(), bytes.ConvertTo2&lt;ulong&gt;(), bytes.ConvertTo1&lt;ulong&gt;() == bytes.ConvertTo2&lt;ulong&gt;());
    }
}


In your Program (or wherever):

CR_101636._Main(args);