Search code examples
c#performanceexecution-time

C# takes more time to do first execution


I have noticed an unusual thing with my C# app. The first time I execute some code takes a lot longer than subsequent executions. Can anyone explain to me why this is?

It is even visible with my simple test app below where I get an initial output of around 13 and subsequent outputs of around 3.

Stopwatch sw;
int count = 0;
private void Window_KeyUp(object sender, KeyEventArgs e)
{
    RunTest();
}

private void RunTest()
{
    sw = Stopwatch.StartNew();
    count = 0;
    for (int i = 0; i < 100; i++)
    {
        count++;
    }
    Console.WriteLine(sw.ElapsedTicks);
}

Solution

  • The first execution includes the time that the Just In Time (JIT) compiler spends converting the code from Microsoft's Intermediary Language (previously called MSIL, now called CIL or Common Intermediate Language) into the native executable machine code of whatever machine you're running the code on.

    All subsequent calls are re-using that already compiled code.