Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which solution has better performance: StringBuilder or String Interpolation-Concatenation

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?

like image 262
Filipe Miranda Avatar asked Jul 31 '15 16:07

Filipe Miranda


2 Answers

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.

like image 83
Rex Kerr Avatar answered Sep 24 '22 13:09

Rex Kerr


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.

like image 37
Aivean Avatar answered Sep 23 '22 13:09

Aivean