Speed up byte parsing possible?

We are doing some performance optimizations in our project and with the profiler I came upon the following method:

private int CalculateAdcValues(byte lowIndex)
{
    byte middleIndex = (byte)(lowIndex + 1);
    byte highIndex = (byte)(lowIndex + 2);

    // samples is a byte[]
    retrun (int)((int)(samples[highIndex] << 24) 
        + (int)(samples[middleIndex] << 16) + (int)(samples[lowIndex] << 8));
}

This method is already pretty fast with ~1µs per execution, but it is called ~100.000 times per second and so it takes ~10% of the CPU.

Does anyone have an idea how to further improve this method?

EDIT:

Current solution:

fixed (byte* p = samples)
{
    for (; loopIndex < 61; loopIndex += 3)
    {
        adcValues[k++] = *((int*)(p + loopIndex)) << 8;
    }
}

This takes <40% of the time then before (the "whole method" took ~35µs per call before and ~13µs now). The for-loop actualy takes more time then the calcualtion now...

Jon Skeet
people
quotationmark

I strongly suspect that after casting to byte, your indexes are being converted back to int anyway for use in the array indexing operation. That will be cheap, but may not be entirely free. So get rid of the casts, unless you were using the conversion to byte to effectively get the index within the range 0..255. At that point you can get rid of the separate local variables, too.

Additionally, your casts to int are no-ops as the shift operations are only defined on int and higher types.

Finally, using | may be faster than +:

private int CalculateAdcValues(byte lowIndex)
{
    return (samples[lowIndex + 2] << 24) |
           (samples[lowIndex + 1] << 16) |
           (samples[lowIndex] << 8);

}

(Why is there nothing in the bottom 8 bits? Is that deliberate? Note that the result will end up being negative if samples[lowIndex + 2] has its top bit set - is that okay?)

people

See more on this question at Stackoverflow