Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#: Why is a function call faster than manual inlining?

I have measured the execution time for two ways of calculating the power of 2:

1) Inline

result = b * b;

2) With a simple function call

result = Power(b);

When running in Debug mode, everything is as expected: Calling a function is considerably more expensive than doing the calculation in line (385 ms in line vs. 570 ms function call).

In release mode, I'd expect the compiler to speed up execution time of the function call considerably because the compiler would inline internally the very small Power() function. But I'd NOT expect the function call to be FASTER than the manual inlined calculation.

Most astonishingly this is the case: In the release build, the first run needs 109 ms and the second run with the call to Power() needs only 62 ms.

How can a function call be faster than manual inlining?

Here is the program for your reproduction:

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Starting Test");

        // 1. Calculating inline without function call
        Stopwatch sw = Stopwatch.StartNew();

        for (double d = 0; d < 100000000; d++)
        {
            double res = d * d;
        }

        sw.Stop();
        Console.WriteLine("Checked: " + sw.ElapsedMilliseconds);

        // 2. Calulating power with function call
        Stopwatch sw2 = Stopwatch.StartNew();

        for (int d = 0; d < 100000000; d++)
        {
            double res = Power(d);
        }

        sw2.Stop();
        Console.WriteLine("Function: " + sw2.ElapsedMilliseconds);

        Console.ReadKey();
    }

    static double Power(double d)
    {
        return d * d;
    }
}
like image 317
Knasterbax Avatar asked Mar 25 '13 10:03

Knasterbax


1 Answers

Your test is wrong. In the second part you use a int d instead of a double. Maybe it explains the time difference.

like image 199
Xavier Delamotte Avatar answered Oct 21 '22 23:10

Xavier Delamotte