哪种解决方案具有更好的性能:StringBuilder或String Interpolation-Concatenation

时间:2015-07-31 16:54:40

标签: string scala stringbuilder string-interpolation

我正在使用Scala将文件写入磁盘。

要创建将写入文件的整个String,我正在迭代我的数据并将所有信息附加到StringBuilder对象。

例如:

val moreData = getMoreData
strBuilder.append(moreData)
strBuilder.append("even more data")
//...
strBuilder.toString

在操作结束时,我调用StringBuilder的toString方法,然后写入Path。

我知道Scala对字符串进行了编译优化,所以我的问题是:

哪种方法具有更好的性能。 String-Interpolation-Concatenation或StringBuilder?

这些编译优化是否与StringBuilder有某种关联?换句话说,是否存在StringBuilder附加操作的优化?

2 个答案:

答案 0 :(得分:5)

字符串插值连接使用StringBuilder生成其结果。可以更多地优化字符串插值,但就目前而言,它主要是为表现力而非性能而设计的。如果您知道字符串创建将会受到限制,那么您应该使用StringBuilder,并且这样做并不难。如果您知道,或者您知道它不是主要问题,则字符串插值通常更容易阅读,因此您在大多数情况下应该更喜欢它。

答案 1 :(得分:1)

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.