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);
}
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With