c# - fixed statement performance / penalty

  • Thread starter Thread starter Arthur Mnev
  • Start date Start date
A

Arthur Mnev

This is probably beaten to death subject...

Does anyone have a good idea of what penalties are for using Fixed
statement in c#. On one side it allows for much greater flexibility
with casts and array manipulations (i'm leaving access to legacy code
out of the scope of this message) on the other hand fixed statement
does consume resources to execute, not to mention if "everything" is
fixed, then dynamic object reallocation becomes impossible, thus
removing a good portion of .net internal memory management
optimizations. Did anyone have any gains / degradations in large scale
implementation with "fixed" vs. "proper" implementations?

Thx.
 
Maybe a more important question is why would you want to use this statement
and when is it justified necessary to use it?
I had never heard of the statement before :|

Greetz,
-- Rob.
 
Rob,

Fixed statement is used in unsafe code to obtain a pointer to a memory
location that otherwise is volatile. .NET runtime can reallocate any
object to a more suitable location at any time, therefore, if you want
to work with memory directly (or as directly as .NET allows you) you
need to fix an object to prevent runtime from moving it elsewhere.
Where would it be used ... lets see a very typical example - read an
array of structures from a file, cast an array of bytes into array of
integers etc...

Example, - assume that you need to perform an operation with an
integer but have an array of bytes.

in a traditional scenario, you would need to loop through byte array,
using BitConverter class convert a set of 4 bytes into an integer.
That is costly as every time you would loop you would have to make a
copy of the value; instead:

byte[] mybytearr = new byte[100];

public static Main()
{
IntWorks(mybytearr);
}

public unsafe void IntWorks(byte[] byteArray)
{
Int32 f_integer_to_work_on = 0;
fixed (byte* byteArrayPtr = byteArray)
{
for (op_counter = 0; op_counter < (byteArray / sizeof(Int32));
op_counter++)
{
f_integer_to_work_on = (Int32*) byteArrayPtr[op_counter];
// do some work here with that integer
// done
}
}
}

as you can see there is no data copying involved as you obtain a
reference to a memory location and treat it as if it was integer.
Naturally you need to make sure that you dont try to access location
past the real array, but then again, it is just following the rules of
programming.

hope it helps.
 
Minor correction
Line: f_integer_to_work_on = (Int32*) byteArrayPtr[op_counter];
Should read: f_integer_to_work_on = ((Int32*) byteArrayPtr)[op_counter];
 
Still doesnt answer my original question :) any idea on how much
overhead fixing an object is?
 
Back
Top