Scala 中的字符串连接是否与 Java 中的字符串连接一样昂贵? [英] Is string concatenation in scala as costly as it is in Java?
问题描述
在 Java 中,由于使用 + 运算符附加字符串的性能不佳,因此使用 StringBuilder 进行字符串连接是一种常见的最佳做法.是否为 Scala 推荐了相同的做法,或者该语言是否改进了 java 如何执行其字符串连接?
In Java, it's a common best practice to do string concatenation with StringBuilder due to the poor performance of appending strings using the + operator. Is the same practice recommended for Scala or has the language improved on how java performs its string concatenation?
推荐答案
Scala 使用 Java 字符串(java.lang.String
),因此它的字符串连接与 Java 的相同:相同的是两者都发生.(毕竟运行时是一样的.)Scala中有一个特殊的StringBuilder
类,它提供了一个与java.lang.StringBuilder
兼容的API";见 http://www.scala-lang.org/api/2.7.5/scala/StringBuilder.html.
Scala uses Java strings (java.lang.String
), so its string concatenation is the same as Java's: the same thing is taking place in both. (The runtime is the same, after all.) There is a special StringBuilder
class in Scala, that "provides an API compatible with java.lang.StringBuilder
"; see http://www.scala-lang.org/api/2.7.5/scala/StringBuilder.html.
但就最佳实践"而言,我认为大多数人通常会认为编写简单、清晰的代码比最高效的代码更好,除非存在实际性能问题或有充分理由期待.+
运算符并没有真正的性能差",只是 s += "foo"
等价于 s = s + "foo"
(即它创建一个新的 String
对象),这意味着,如果您对(看起来像)单个字符串"进行大量连接,则可以避免创建不必要的对象并反复将前面的部分从一个字符串重新复制到另一个字符串中—通过使用 StringBuilder
而不是 String
.通常差异并不重要.(当然,简单、清晰的代码"有点矛盾:使用 +=
更简单,使用 StringBuilder
更清晰.但是,通常还是应该根据代码来决定- 编写注意事项而不是次要的性能注意事项.)
But in terms of "best practices", I think most people would generally consider it better to write simple, clear code than maximally efficient code, except when there's an actual performance problem or a good reason to expect one. The +
operator doesn't really have "poor performance", it's just that s += "foo"
is equivalent to s = s + "foo"
(i.e. it creates a new String
object), which means that, if you're doing a lot of concatenations to (what looks like) "a single string", you can avoid creating unnecessary objects — and repeatedly recopying earlier portions from one string to another — by using a StringBuilder
instead of a String
. Usually the difference is not important. (Of course, "simple, clear code" is slightly contradictory: using +=
is simpler, using StringBuilder
is clearer. But still, the decision should usually be based on code-writing considerations rather than minor performance considerations.)
这篇关于Scala 中的字符串连接是否与 Java 中的字符串连接一样昂贵?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!