Reputation: 19690
There are at least 3 ways a string can be built in F#:
Which one should I stick to in F#?
Upvotes: 3
Views: 498
Reputation: 11525
In general, you should use the printf
-based functions (e.g., sprintf
, bprintf
) in F# code they're type-safe: the compiler checks the format strings at compile-time and makes sure you're passing the correct argument types.
This does have one drawback, however -- in F# 2.0 and 3.0, the printf
-based functions are quite slow (search StackOverflow or Google, you'll find questions and blog posts about it). They won't impact the overall performance of your application if you use them occasionally, but if you're calling them frequently you will notice your application slowing down. Thankfully, this has been fixed for the upcoming F# 3.1 release.
As for the other options, you should avoid string concatenation whenever possible, as it's relatively slow and also incurs extra memory/GC overhead. If you're implementing some performance-sensitive logging and you can't wait for F# 3.1, then String.Format is your best bet; to mimic the type-safety provided by the printf
-based functions, you could move each of your calls to String.Format into a separate function, then explicitly specify the parameter types with a type annotation. For example:
/// Prints the number of entries in a specified file to the console.
let inline printNumEntriesInFile (filename : string) (count : int) =
System.String.Format ("The file '{0}' contains {1} entries.", filename, count)
Upvotes: 6