printfn
and its various cousins have several advantages:
- They're shorter.
- They can do some static type checking; i.e.
printfn "%d" "bad type"
will not compile.
- ...but you don't have to do static type checking;
%O
prints any object
- They can print "smart" representations for things like arrays, tuples, and discriminated unions with
%A
- They can be partially applied; i.e.
printfn "%d, %d" 3
is a valid expression. This is particularly nifty since the compiler can check that you actually apply the right number of arguments when you later use this subexpression - unlike Console.WriteLine
which will happily accept too many or too few parameters.
In practice, the most common partial application is likely to include just the format string; e.g.
let printParticle = printfn "Particle at (%d, %d), state %A, p = %f"
printParticle 2 3 //compile time warning about ignored value
printParticle 3 4 someState 0.4 //fine
printParticle 5 6 someState 0.4 0.7 //compile-time error
However, prior to F# 3.1, it's also slow. It's plenty fast enough to keep up with you the coder, but if you're using it in some form of serialization, it could turn into a bottleneck. The F# 3.1 release announcement (which is distributed as part of Visual Studio 2013) claims to improve the performance dramatically, though I have not verified this.
Personally, I usually use printfn for exploratory coding, and then I largely stick to %A
with the occasional other specifier thrown in. However, the .NET native string formatting is still useful in some cases for its detailed culture and formatting-related options. If you want maximum speed direct concatenation (or a StringBuilder
) will easily outperform both as this avoids interpreting the format string.
printf
orWriteLine
printfn
.