【发布时间】:2021-07-08 03:46:52
【问题描述】:
对于只包含一个 byte 字段的结构,我希望该结构在内存中消耗 1 个字节。如果我创建一个该结构类型的数组,结果证明这是一个准确的预期。当将该结构用作类中的字段时,我有同样的期望,但是,令我惊讶的是,每个字段都占用了IntPtr 的大小!我认为这只会发生由于将类填充到下一个字长,但无论如何似乎都是这种情况。这是为什么呢?
[编辑] 更新的测量值
| Method | Mean | Error | StdDev | Gen 0 | Gen 1 | Gen 2 | Allocated |
|---|---|---|---|---|---|---|---|
| AllocOneByte | 7.453 ns | 0.0885 ns | 0.0827 ns | 0.0076 | - | - | 24 B |
| AllocTwoBytes | 8.394 ns | 0.0873 ns | 0.0816 ns | 0.0076 | - | - | 24 B |
| AllocThreeBytes | 8.398 ns | 0.0559 ns | 0.0523 ns | 0.0076 | - | - | 24 B |
| AllocOneByteWrapper | 8.373 ns | 0.0934 ns | 0.0873 ns | 0.0076 | - | - | 24 B |
| AllocTwoByteWrappers | 9.815 ns | 0.1256 ns | 0.1175 ns | 0.0102 | - | - | 32 B |
| AllocThreeByteWrappers | 11.274 ns | 0.1527 ns | 0.1429 ns | 0.0127 | - | - | 40 B |
| AllocOneByteArray | 9.286 ns | 0.1609 ns | 0.1505 ns | 0.0102 | - | - | 32 B |
| AllocTwoBytesArray | 9.396 ns | 0.1038 ns | 0.0920 ns | 0.0102 | - | - | 32 B |
| AllocThreeBytesArray | 8.904 ns | 0.1183 ns | 0.1107 ns | 0.0102 | - | - | 32 B |
public class Benchmark
{
public class OneByte
{
public byte num;
}
public class TwoBytes
{
public byte num;
public byte num2;
}
public class ThreeBytes
{
public byte num;
public byte num2;
public byte num3;
}
public struct ByteWrapper
{
public byte num;
}
public class OneByteWrapper
{
public ByteWrapper num;
}
public class TwoByteWrappers
{
public ByteWrapper num;
public ByteWrapper num2;
}
public class ThreeByteWrappers
{
public ByteWrapper num;
public ByteWrapper num2;
public ByteWrapper num3;
}
[Benchmark]
public OneByte AllocOneByte()
{
return new OneByte();
}
[Benchmark]
public TwoBytes AllocTwoBytes()
{
return new TwoBytes();
}
[Benchmark]
public ThreeBytes AllocThreeBytes()
{
return new ThreeBytes();
}
[Benchmark]
public OneByteWrapper AllocOneByteWrapper()
{
return new OneByteWrapper();
}
[Benchmark]
public TwoByteWrappers AllocTwoByteWrappers()
{
return new TwoByteWrappers();
}
[Benchmark]
public ThreeByteWrappers AllocThreeByteWrappers()
{
return new ThreeByteWrappers();
}
[Benchmark]
public ByteWrapper[] AllocOneByteArray()
{
return new ByteWrapper[1];
}
[Benchmark]
public ByteWrapper[] AllocTwoBytesArray()
{
return new ByteWrapper[2];
}
[Benchmark]
public ByteWrapper[] AllocThreeBytesArray()
{
return new ByteWrapper[3];
}
}
[Edit2] 这与Why isn't sizeof for a struct equal to the sum of sizeof of each member? 不同。这是关于使用小型结构作为类中的字段。
【问题讨论】:
-
@jdweng 结构绝对没有有标题。除非你在谈论拳击,但问题不在于拳击。
-
@Tim 对上述评论:您可以在引用字段上使用显式布局,但它们仍需要对齐;如果您的代码可以同时在 x64 和 x86 上运行,那么这样做也会真的很混乱,所以实际上:人们不会倾向于这样做,除非他们只有一个可以攻击的参考字段结构的结尾
-
@jdweng 有时我没有应有的观察力;您能否明确说明您指的是哪个盒子?我已经阅读了 OP 的帖子 3 次,我看不到一个拳击操作。我不认为这与拳击有任何关系,但我很高兴得到纠正。
-
@jdweng 给我看盒子;显示的代码中有 零 个框