C # Indicative strange case

I tested some cases in C # to consider some essential aspects of performance. While I tested, I came across a strange case

for (int i = 0; i < 30; i++) { DateTime d = DateTime.Now; print(); result.Add ((DateTime.Now - d)); } foreach(TimeSpan t in result) Console.WriteLine(t.ToString()); 

while the print function was simple:

 public static void print () { for (int i = 0; i < 10000; i++) { Console.WriteLine( string.Format("{0}", i)); } } 

i was shocked by the results, while the first three loops took about 5 seconds, and after that it took about 0.5 seconds. Here is some of them:

 00:00:05.6212696 00:00:05.6072002 00:00:05.5837965 00:00:01.9451673 00:00:00.5526335 00:00:00.5540554 00:00:00.5676418 00:00:00.5372442 00:00:00.5772550 

I just want to know why it got better almost 10 times after the third iteration?

+4
source share
2 answers

I just run the same code on my PC and get the following output:

 00:00:00.0469083 00:00:00.0312722 00:00:00.0312722 00:00:00.0469083 00:00:00.0312722 00:00:00.0312722 00:00:00.0312722 00:00:00.0469083 .... 

As you can see, there is no noticeable difference. I would say, first, do not waste time checking performance for such cases, as it can vary from PC to PC and repeat John’s suggestion to use StopWatch for a more accurate measurement.

+3
source

Your bottleneck here will be Console.WriteLine . Various things can affect this, but in particular, if you minimized the window or something like that, this could significantly speed up the process.

Are you sure you are really measuring something useful? Does your application in the real world write a lot to the console?

Please note that it is usually better to use Stopwatch than DateTime.Now to measure performance, although this will not make much difference here.

+8
source

Source: https://habr.com/ru/post/1397743/


All Articles