In the current project of my work, I have to parse the string and write its parts to the console. Checking how to do this without extra costs, I found that one of the methods I tested was actually faster than Console.WriteLine, which confuses me a bit.
I know that this is not the right way to test, but I usually have a good understanding of the rough βit's faster than thatβ, which I can say after several times.
static void Main(string[] args) { var timer = new Stopwatch(); timer.Restart(); Test1("just a little test string."); timer.Stop(); Console.WriteLine(timer.Elapsed); timer.Restart(); Test2("just a little test string."); timer.Stop(); Console.WriteLine(timer.Elapsed); timer.Restart(); Test3("just a little test string."); timer.Stop(); Console.WriteLine(timer.Elapsed); } static void Test1(string str) { Console.WriteLine(str); } static void Test2(string str) { foreach (var c in str) Console.Write(c); Console.Write('\n'); } static void Test3(string str) { using (var stream = new StreamWriter(Console.OpenStandardOutput())) { foreach (var c in str) stream.Write(c); stream.Write('\n'); } }
As you can see, Test1 uses Console.WriteLine. My first thought was to just call Write for each char, see Test2. But this led to getting about twice as long. My guess would be that it erases after each recording, which makes it slower. So I tried Test3 using StreamWriter (AutoFlush off), which led to 25% faster than Test1, and I'm really curious what it is. Or maybe recording to the console cannot be verified correctly? (noticed some strange data when adding additional test cases ...)
Can someone enlighten me?
Also, if there is a better way to do this (going through a line and only writing parts of it to the console), feel free to comment on it.
Mars
source share