Why is F# printfn not implemented in terms of Console.WriteLine?
Asked Answered
R

1

3

I noticed an unexpected behavior when using F# printfn. It seems to break up the format string into chunks and call Console.Write multiple times for each call to printfn. I would expect it to format the entire string and then call Console.WriteLine once.

I noticed this because I am intercepting the standard Console Output using Console.SetOut call with my own TextWriter which tries to prefix every line of output with a time stamp and some additional custom text.

What gives?

Recount answered 12/9, 2016 at 22:4 Comment(3)
Check this post, it seems to suggest it has something to do with data validation: #18552351Agnosticism
If you want to prefix each line, you should accumulate the text until WriteLine is called. What's your problem?Ardor
Yep I could do that, but I am just wondering why it behaves the way it does. Why was it implemented like this? To me it seems to be much more straight forward to implement it in terms of WriteLine single call for entire line of text. Instead of breaking it up into chunks which is much less efficient and also creates counter intuitive behaviorRecount
I
0

Here's my guess, for what it's worth:

  1. Compiler does some magic
  2. At runtime, implementer knew that Write will go to a buffered stream, so that performance won't be drastically different from using something like a StringBuilder object and its ToString() override. Maybe performance is even better, since they avoided an object allocation.
Ilona answered 13/9, 2016 at 16:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.