atl*_*ste 14 .net c# generics memory-management value-type
我总是理解结构(值类型)包含结构字段中定义的字节数...但是,我做了一些测试,并且空结构似乎有一个例外:
public class EmptyStructTest
{
static void Main(string[] args)
{
FindMemoryLoad<FooStruct>((id) => new FooStruct());
FindMemoryLoad<Bar<FooStruct>>((id) => new Bar<FooStruct>(id));
FindMemoryLoad<Bar<int>>((id) => new Bar<int>(id));
FindMemoryLoad<int>((id) => id);
Console.ReadLine();
}
private static void FindMemoryLoad<T>(Func<int, T> creator) where T : new()
{
GC.Collect(GC.MaxGeneration);
GC.WaitForFullGCComplete();
Thread.MemoryBarrier();
long start = GC.GetTotalMemory(true);
T[] ids = new T[10000];
for (int i = 0; i < ids.Length; ++i)
{
ids[i] = creator(i);
}
long end = GC.GetTotalMemory(true);
GC.Collect(GC.MaxGeneration);
GC.WaitForFullGCComplete();
Thread.MemoryBarrier();
Console.WriteLine("{0} {1}", ((double)end-start) / 10000.0, ids.Length);
}
public struct FooStruct { }
public struct Bar<T> where T : struct
{
public Bar(int id) { value = id; thing = default(T); }
public int value;
public T thing;
}
}
Run Code Online (Sandbox Code Playgroud)
如果你运行程序,你会发现显然有0字节数据的en FooStruct会消耗1个字节的内存.这对我来说是个问题的原因是我想要Bar<FooStruct>消耗4个字节(因为我要分配很多).
为什么它有这种行为并且有办法解决这个问题(例如,是否存在消耗0字节的特殊事物 - 我不是在寻找重新设计)?
Gle*_*den 11
简介:.NET中的空结构占用1个字节.您可以将其视为packing,因为未命名的字节只能通过不安全的代码访问.
更多信息:如果你根据.NET报告的值执行所有指针算术,那么事情就会一直有效.
以下示例说明了在堆栈上使用相邻的0字节结构,但这些观察结果显然也适用于0字节结构的数组.
struct z { };
unsafe static void foo()
{
var z3 = default(z);
bool _;
long cb_pack, ?z, cb_raw;
var z2 = default(z); // (reversed since stack offsets are negative)
var z1 = default(z);
var z0 = default(z);
// stack packing differs between x64 and x86
cb_pack = (long)&z1 - (long)&z0; // --> 1 on x64, 4 on x86
// pointer arithmetic should give packing in units of z-size
?z = &z1 - &z0; // --> 1 on x64, 4 on x86
// if one asks for the value of such a 'z-size'...
cb_raw = Marshal.SizeOf(typeof(z)); // --> 1
// ...then the claim holds up:
_ = cb_pack == ?z * cb_raw; // --> true
// so you cannot rely on special knowledge that cb_pack==0 or cb_raw==0
_ = &z0 /* + 0 */ == &z1; // --> false
_ = &z0 /* + 0 + 0 */ == &z2; // --> false
// instead, the pointer arithmetic you meant was:
_ = &z0 + cb_pack == &z1; // --> true
_ = &z0 + cb_pack + cb_pack == &z2; // --> true
// array indexing also works using reported values
_ = &(&z0)[?z] == &z1; // --> true
// the default structure 'by-value' comparison asserts that
// all z instances are (globally) equivalent...
_ = EqualityComparer<z>.Default.Equals(z0, z1); // --> true
// ...even when there are intervening non-z objects which
// would prevent putative 'overlaying' of 0-sized structs:
_ = EqualityComparer<z>.Default.Equals(z0, z3); // --> true
// same result with boxing/unboxing
_ = Object.Equals(z0, z3); // -> true
// this one is never true for boxed value types
_ = Object.ReferenceEquals(z0, z0); // -> false
}
Run Code Online (Sandbox Code Playgroud)
正如我在评论中提到的那样,当@supercat指出,"设计.NET从一开始就允许零长度结构可能不会有任何问题,但可能会有一些东西会破坏如果它现在开始这样做."
编辑:如果您需要以编程方式区分0字节和1字节值类型,您可以使用以下内容:
public static bool IsZeroSizeStruct(Type t)
{
return t.IsValueType && !t.IsPrimitive &&
t.GetFields((BindingFlags)0x34).All(fi => IsZeroSizeStruct(fi.FieldType));
}
Run Code Online (Sandbox Code Playgroud)
请注意,这可以正确识别任意嵌套的结构,其中总大小为零.
[StructLayout(LayoutKind.Sequential)]
struct z { };
[StructLayout(LayoutKind.Sequential)]
struct zz { public z _z, __z, ___z; };
[StructLayout(LayoutKind.Sequential)]
struct zzz { private zz _zz; };
[StructLayout(LayoutKind.Sequential)]
struct zzzi { public zzz _zzz; int _i; };
/// ...
c = Marshal.SizeOf(typeof(z)); // 1
c = Marshal.SizeOf(typeof(zz)); // 3
c = Marshal.SizeOf(typeof(zzz)); // 3
c = Marshal.SizeOf(typeof(zzzi)); // 8
_ = IsZeroSizeStruct(typeof(z)); // true
_ = IsZeroSizeStruct(typeof(zz)); // true
_ = IsZeroSizeStruct(typeof(zzz)); // true
_ = IsZeroSizeStruct(typeof(zzzi)); // false
Run Code Online (Sandbox Code Playgroud)
[编辑:参见注释] 这里奇怪的是,当嵌套0字节结构时,单字节最小值可以累加(即'zz'和'zzz'为3个字节),但突然之间所有的chaff都会消失作为单个"实质"字段包括在内.
这与C(或C++)中不允许零大小的对象的原因相同:指针算术的元素数量.
C#支持不安全块中的指针减法,因此定义如下:
给定两个表达式,
P以及Q指针类型T*,表达式P – Q计算由P和给出的地址之间的差异Q,然后将该差异除以sizeof(T).
由于无法除以零,这意味着sizeof(T) > 0对所有人而言T.
| 归档时间: |
|
| 查看次数: |
3841 次 |
| 最近记录: |