Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Performance weird case

I was testing some cases in C# to consider some essentials in performance, While i was testing i faced a weird 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 simply :

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

i was shocked with the results while the first three loops it took about 5 seconds while after that it took about 0.5 sec. Here is some :

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 by almost 10 times after the third iteration?

like image 985
Hilmi Avatar asked Dec 21 '22 01:12

Hilmi


1 Answers

Your bottleneck here is going to be Console.WriteLine. Various things could affect that, but in particular if you minimized the window or something similar, that could massively speed things up.

Are you sure you're really measuring anything useful? Does your real world application do a lot of writing to the console?

Note that it's generally better to use Stopwatch than DateTime.Now for measuring performance, although it wouldn't make much of a difference here.

like image 64
Jon Skeet Avatar answered Dec 23 '22 14:12

Jon Skeet