Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to copy class fields with unsafe

Tags:

c#

unsafe

I have two classes

[StructLayout(LayoutKind.Explicit, Size = 12, CharSet = CharSet.Ansi)]
unsafe class Dto
{
    [FieldOffset(0)]
    public int B;
    [FieldOffset(4)]
    public int C;
    [FieldOffset(8)]
    public int D;
}
[StructLayout(LayoutKind.Explicit, Size = 12, CharSet = CharSet.Ansi)]
unsafe class Model
{
    [FieldOffset(0)]
    public int B;
    [FieldOffset(4)]
    public int C;
    [FieldOffset(8)]
    public int D;
}

Is there the way to copy data from fields from instance of DTO o instance of Model? For a single field I have following code

var a1 = new Dto { B = 10, C = 20, D = 30 };
var a2 = new Model();

unsafe
{
     fixed (int* pa1 = &(a1.B))
     {
          fixed (int* pa2 = &(a2.B))
          {
               *pa2 = *pa1;
          }
     }
 }

Does C# provide similar method to copy whole object? Copy field-by-field is not desirable due to high performance environment.

like image 570
Alexey.Popov Avatar asked Nov 10 '22 07:11

Alexey.Popov


1 Answers

Your main concern is performance. If you copy field-by-field, this will translate to 6 mov instructions. It is very hard to make it faster then this.

Using pointers does not reduce the number of instructions required. Why would it? You still need the same assignments.

Calling memcpy involves far more overhead then the trivial 6 mov instructions.

So you should write the "naive" three assignments using safe managed code to get optimal performance. In fact, copying this 12-byte object is so cheap that I doubt your performance concerns are valid. I doubt this will show up on any profile.

For copy performance it does not matter whether you use class or struct. But struct has certain performance benefits due to other differences. You might want to investigate them.

like image 66
usr Avatar answered Nov 14 '22 22:11

usr