It seems Console.WriteLine(...)
is really slow in C#.
Here's the code I tested.
var iterations = 5000;
var watch = new Stopwatch();
watch.Start();
for (int i = 0; i < iterations; i++)
Console.WriteLine("adsdsaddhfuihdsuifhdsufudshfoadfdshoadsuoadsuioadsihfuidh");
watch.Stop();
double msPerOp = 1.0 * watch.ElapsedMilliseconds / iterations;
Console.WriteLine("{0} ms/op", msPerOp);
In my laptop, it prints 5.731 ms/op
.
Why is it so slow?
As far as I know, printing to console in other languages is not this slow.
For example, in Go, fmt.Println(...)
with same string only takes 416275 ns/op (= 0.416275 ms/op)
in my laptop.
(tested with go test -bench .
)
Why is Console.WriteLine(...)
so slow in c#? Is there any alternative I can use which has a performance similar with Go's fmt.Println(...)
?
EDIT)
The reason I need fast Console.WriteLine(...)
is following.
My application continuously receives a lots of real time data (20~80 data/sec) by windows message loop, and I want to simply print the data every time I receive with Console.WriteLine
. I should print it fast because if not, real time data gets delayed.
However, it seems Console.WriteLine(...)
takes 5~10ms (for long string).. and this is too slow for real time data processing.