我正在使用 BenchmarkDotNet 及其 MemoryDiagnoser 功能。
考虑以下基准:
[Benchmark]
public void Dummy()
{
var buffer = new byte[1];
}
我希望它恰好分配 1 个字节。
但是基准测试结果显示总共分配了 32 个字节。怎么来的?我觉得这很有误导性。
| Method | Mean | Error | StdDev | Median | Ratio | Rank | Gen 0 | Gen 1 | Gen 2 | Allocated |
|------- |---------:|----------:|----------:|---------:|------:|-----:|-------:|------:|------:|----------:|
| Dummy | 4.486 ns | 0.1762 ns | 0.5196 ns | 4.650 ns | 1.00 | 1 | 0.0038 | - | - | 32 B |
why not 1 byte? ^^^^
最佳答案
我是 MemoryDiagnoser 的作者,我已经描述了如何阅读我的博客的结果:https://adamsitnik.com/the-new-Memory-Diagnoser/#how-to-read-the-results
CLR does some aligning. If you try to allocate new byte[1] array, it will allocate byte[8] array.
We need extra space for object header, method table pointer and length of the array. The overhead is 3x Pointer Size. 8 + 3x4 = 20 for 32bit and 8 + 3x8 = 32 for 64bit.
关于c# - 为什么分配的内存比预期的多?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60249021/