-
Notifications
You must be signed in to change notification settings - Fork 272
/
NoThrowInline.cs
53 lines (46 loc) · 1.82 KB
/
NoThrowInline.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Runtime.CompilerServices;
using BenchmarkDotNet.Attributes;
using MicroBenchmarks;
namespace Inlining
{
[BenchmarkCategory(Categories.Runtime, Categories.Inlining)]
public class NoThrowInline
{
static void ThrowIfNull(string s)
{
if (s == null)
ThrowArgumentNullException();
}
static void ThrowArgumentNullException()
{
throw new ArgumentNullException();
}
//
// We expect ThrowArgumentNullException to not be inlined into Bench, the throw code is pretty
// large and throws are extremly slow. However, we need to be careful not to degrade the
// non-exception path performance by preserving registers across the call. For this the compiler
// will have to understand that ThrowArgumentNullException never returns and omit the register
// preservation code.
//
// For example, the Bench method below has 4 arguments (all passed in registers on x64) and fairly
// typical argument validation code. If the compiler does not inline ThrowArgumentNullException
// and does not make use of the "no return" information then all 4 register arguments will have
// to be spilled and then reloaded. That would add 8 unnecessary memory accesses.
//
[MethodImpl(MethodImplOptions.NoInlining)]
static int Bench(string a, string b, string c, string d)
{
ThrowIfNull(a);
ThrowIfNull(b);
ThrowIfNull(c);
ThrowIfNull(d);
return a.Length + b.Length + c.Length + d.Length;
}
[Benchmark(Description = nameof(NoThrowInline))]
public int Test() => Bench("a", "bc", "def", "ghij");
}
}