大对象和finalzier对象创建相比小对象会更慢
《Pro .NET Memory Management》 Chapter6 P428 中讲道大对象(包括Obj对象头部等,总字节占85000及以上)和有finalizer的对象生成的构造函数(JIT_New)会更为复杂,因此开销会更大。对此做了验证。小对象使用辅助函数JIT_TrialAllocSFastMP_InlineGetThread生成构造函数。
BenchmarkDotNet=v0.13.2, OS=Windows 11 (10.0.22621.521)
Intel Core i5-9300H CPU 2.40GHz, 1 CPU, 8 logical and 4 physical cores
.NET SDK=6.0.200
[Host] : .NET 6.0.2 (6.0.222.6406), X64 RyuJIT AVX2
DefaultJob : .NET 6.0.2 (6.0.222.6406), X64 RyuJIT AVX2
| Method | Mean | Error | StdDev | Ratio | RatioSD |
|----------------- |-------------:|-----------:|------------:|---------:|--------:|
| SmallObj | 2.384 ns | 0.0408 ns | 0.0361 ns | 1.00 | 0.00 |
| SmallObj400B | 19.388 ns | 0.4611 ns | 0.5996 ns | 8.07 | 0.22 |
| SmallObj4000B | 172.992 ns | 3.5460 ns | 4.0836 ns | 72.59 | 1.93 |
| LargeObj88000B | 4,934.280 ns | 95.6147 ns | 102.3067 ns | 2,067.26 | 43.73 |
| SmallObjFinalize | 145.863 ns | 3.0032 ns | 6.7788 ns | 62.26 | 3.88 |
public class SmallWithFinalizer
{
int val;
~SmallWithFinalizer()
{
}
}
public class Small
{
int val;
}
public class FinalizerObjCost
{
[Benchmark(Baseline = true)]
public Small SmallObj()
{
return new Small();
}
[Benchmark]
public int[] SmallObj400B()
{
var intArray = new int[100];
return intArray;
}
[Benchmark]
public int[] SmallObj4000B()
{
var intArray = new int[1000];
return intArray;
}
[Benchmark]
public int[] LargeObj88000B()
{
int[] intArray = new int[22000];
return intArray;
}
[Benchmark]
public SmallWithFinalizer SmallObjFinalize()
{
return new SmallWithFinalizer();
}
}