Skip to content

Instantly share code, notes, and snippets.

@ufcpp
Created February 26, 2025 14:24
Show Gist options
  • Save ufcpp/e028817e05c7fab2b2aff310f7a0293d to your computer and use it in GitHub Desktop.
Save ufcpp/e028817e05c7fab2b2aff310f7a0293d to your computer and use it in GitHub Desktop.
Nullable<T> のコスト高すぎると思うの
using System.Runtime.CompilerServices;
#if false
M(new A { X = 1 });
M(new B { X = 1 });
M(new A { Y = 2 });
M(new B { Y = 2 });
M(new A { X = 1, Y = 2 });
M(new B { X = 1, Y = 2 });
M(new A { });
M(new B { });
static void M<T>(T x) where T : IA
{
Console.WriteLine($"{x.X} {x.Y}");
}
#endif
Console.WriteLine(Unsafe.SizeOf<A>()); // 40
Console.WriteLine(Unsafe.SizeOf<B>()); // 16
interface IA
{
byte? W { get; set; }
int? X { get; set; }
long? Y { get; set; }
short? Z { get; set; }
}
struct A : IA
{
public byte? W { get; set; }
public int? X { get; set; }
public long? Y{ get; set; }
public short? Z { get; set; }
}
struct B : IA
{
private byte _flags;
private byte _w;
private short _z;
private int _x;
private long _y;
public int? X
{
get => (_flags & 1) != 0 ? _x : null;
set
{
if (value.HasValue)
{
_flags |= 1;
_x = value.Value;
}
else
{
_flags &= 0xFE;
}
}
}
public long? Y
{
get => (_flags & 2) != 0 ? _y : null;
set
{
if (value.HasValue)
{
_flags |= 2;
_y = value.Value;
}
else
{
_flags &= 0xFD;
}
}
}
public short? Z
{
get => (_flags & 4) != 0 ? _z : null;
set
{
if (value.HasValue)
{
_flags |= 4;
_z = value.Value;
}
else
{
_flags &= 0xFB;
}
}
}
public byte? W
{
get => (_flags & 8) != 0 ? _w : null;
set
{
if (value.HasValue)
{
_flags |= 8;
_w = value.Value;
}
else
{
_flags &= 0xF7;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment