Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
    }
like image 883
user2424495 Avatar asked Mar 09 '15 19:03

user2424495


2 Answers

The first execution includes the time that the Just In Time (JIT) compiler spends converting the code from Microsoft's Intermediary Language (MSIL) 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.

like image 114
Servy Avatar answered Sep 24 '22 13:09

Servy


My comments are late but hope they might help someone.

If you clear up the memory and then run the program again, you will not see the savings you see on subsequent runs.

Here is an example.

I had written a small program that traverses through all the folders on a drive and calculates the total size taken up by the image files. On subsequent runs the program ran much faster as compared to the first run. However there is more to it than the JIT think discussed above.

.Net seems to store an execution plan during the first run and uses it for optimizing subsequent runs. So when I change the folder to e:\work from d:\work, it takes nearly the same time it took for the first run (note - changes to the path are made in config file so no recompiling was required and d:\work is similar in size to e:\work). When the path was changed back to d:\work, .Net executed it in lesser time.

like image 36
Anand Shelke Avatar answered Sep 22 '22 13:09

Anand Shelke