Unsafe C# trick to improve speed

后端 未结 3 2150
花落未央
花落未央 2021-02-19 14:02

I am not used to code with pointers (e.g. C++), nor with unsafe islands: only \"safe\" C#. Now I\'d like to implement a function in C# for the .Net Micro Framework, where the co

3条回答
  •  深忆病人
    2021-02-19 14:45

    I don't think your "trick" is a problem. Nobody cares how you index memory, or how many offsets you use to accomplish it. I do think you need to heed the advice of others and make sure that you are controlling layout of your struct with StructLayout.Sequential, or .Explicit. Watch the Size and Pack options also.

    The other issue, which has been mentioned, is that you need to do all of your work in the fixed block.

    fixed (byte* ptr = struct2.Buffer)
    {
        var structPtr = (MyStruct*)ptr;
        var structIndex = 0;
        do
        {
            Test5(structPtr);
        } while (++structIndex < ArraySize);
    }
    

    Personally, I think you've stumbled into some Micro-Optimization theatre and would be better served by using safe C# code. Based on the numbers that you have given, (224x10^-3 - 177x10^-3) yields 47ms, divided by 5000 iterations nets you 9.4us (9.4x10^-6) per iteration (assuming windows isn't doing something else at the time).

提交回复
热议问题