C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Caution: Please consider the AggressiveInlining option built into the .NET Framework before using this approach.
AggressiveInliningAnd: Method B contains another method call (C) that does part of the execution logic.
Then: Main demonstrates the performance difference between the two first methods.
Info: It shows that manually inlining improves performance by about 1.5 nanoseconds per invocation on the test computer.
C# program that benchmarks inlined method
using System;
using System.Diagnostics;
class Program
{
static int A(int v)
{
// This is a single method call.
// ... It contains twenty increments.
v++; v++; v++; v++; v++; v++; v++; v++; v++; v++;
v++; v++; v++; v++; v++; v++; v++; v++; v++; v++;
return v;
}
static int B(int v)
{
// This does ten increments.
// ... Then it does ten more increments in another method.
v++; v++; v++; v++; v++; v++; v++; v++; v++; v++;
v = C(v);
return v;
}
static int C(int v)
{
// This does ten increments.
v++; v++; v++; v++; v++; v++; v++; v++; v++; v++;
return v;
}
static void Main()
{
const int max = 100000000;
int temp1 = 0;
int temp2 = 0;
A(0);
B(0);
C(0);
var s1 = Stopwatch.StartNew();
for (int i = 0; i < max; i++)
{
temp1 = A(i);
}
s1.Stop();
var s2 = Stopwatch.StartNew();
for (int i = 0; i < max; i++)
{
temp2 = B(i);
}
s2.Stop();
Console.WriteLine(s1.Elapsed.TotalMilliseconds * 1000 * 1000 / (double)max);
Console.WriteLine(s2.Elapsed.TotalMilliseconds * 1000 * 1000 / (double)max);
Console.WriteLine("{0} {1}", temp1, temp2);
Console.Read();
}
}
Output
2.236963 (inlined)
3.820417 (regular method)
100000019 100000019
And: Unfortunately, these method instructions are pure overhead, at least when they are not required for modularity of design.
Tip: This explains the benefit to inlining methods. The just-in-time compiler inlines certain methods, but typically only small ones.