Note that there are some explanatory texts on larger screens.

plurals
  1. POWhat is the overhead of C# fixed statement on a managed unsafe struct containing fixed arrays?
    text
    copied!<p>I've been trying to determine what the true cost of using the fixed statement within C# for managed unsafe structs that contain fixed arrays. Please note I am not referring to unmanaged structs.</p> <p>Specifically, is there any reason to avoid the pattern shown by 'MultipleFixed' class below? Is the cost of simply fixing the data non zero, near zero (== cost similar to setting &amp; clearing a single flag when entering/exiting the fixed scope), or is it significant enough to avoid when possible? </p> <p>Obviously these classes are contrived to help explain the question. This is for a high usage data structure in an XNA game where read/write performance of this data is critical, so if I need to fix the array and pass it around everywhere I'll do that but if there is no difference at all I'd prefer to keep the fixed() local to the methods to help with keeping the function signatures slightly more portable to platforms that don't support unsafe code. (Yeah, its some extra grunt code but whatever it takes..)</p> <pre> unsafe struct ByteArray { public fixed byte Data[1024]; } class MultipleFixed { unsafe void SetValue(ref ByteArray bytes, int index, byte value) { fixed(byte* data = bytes.Data) { data[index] = value; } } unsafe bool Validate(ref ByteArray bytes, int index, byte expectedValue) { fixed(byte* data = bytes.Data) { return data[index] == expectedValue; } } void Test(ref ByteArray bytes) { SetValue(ref bytes, 0, 1); Validate(ref bytes, 0, 1); } } class SingleFixed { unsafe void SetValue(byte* data, int index, byte value) { data[index] = value; } unsafe bool Validate(byte* data, int index, byte expectedValue) { return data[index] == expectedValue; } unsafe void Test(ref ByteArray bytes) { fixed(byte* data = bytes.Data) { SetValue(data, 0, 1); Validate(data, 0, 1); } } } </pre> <p>Also, I looked for similar questions and the closest I found was <a href="https://stackoverflow.com/questions/3323042/what-is-the-overhead-of-the-fixed-statement-when-used-on-an-unmanaged-struct">this</a>, but this question is different in that it is concerned only with pure managed code and the specific costs of using fixed in that context.</p> <p>Thanks for any info!</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload