I am writing files to disk using Scala.
To create the whole String that will be written to the file, I am currently iterating over my data and appending all the information to a StringBuilder object.
for instance:
val moreData = getMoreData
strBuilder.append(moreData)
strBuilder.append("even more data")
//...
strBuilder.toString
At the end of the operation I then call the StringBuilder's toString method, and write to the Path.
I know Scala has compilation optimizations for Strings, so my questions are:
Which approach has the better performance. String-Interpolation-Concatenation or StringBuilder?
Are these compilation optimizations somehow related to StringBuilder? In other words, are there optimizations for StringBuilder append operation?
String interpolation concatenation uses a StringBuilder
to generate its results. It would be possible to optimize string interpolation more, but as it stands it is mostly designed for expressive power, not performance. You should use StringBuilder
if you know that string creation is going to be limiting, and it's not too hard to do so. If you don't know, or you know that it isn't a major issue, string interpolation is usually much easier to read, so you should prefer it in most instances.
The most efficient way to concatenate multiple strings will be using StringBuilder
.
But your task is not about string concatenation. The most efficient way to write multiple strings to file is using good old java's FileWriter
and BufferedWriter
:
val fw = new FileWriter("foo.out")
val bw = new BufferedWriter(fw)
strings.foreach {
s =>
bw.write(s)
}
bw.close()
fw.close()
Optionally you can wrap BufferedWriter
with PrintWriter
if you need formatting functionality.
Of course everything above is true if you prefer performance over code size.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With