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?
相关问题
- Unusual use of the new keyword
- Get Runtime Type picked by implicit evidence
- What's the point of nonfinal singleton objects
- PlayFramework: how to transform each element of a
- Error in Scala Compiler: java.lang.AssertionError:
相关文章
- Gatling拓展插件开发,check(bodyString.saveAs("key"))怎么实现
- RDF libraries for Scala [closed]
- Why is my Dispatching on Actors scaled down in Akk
- How do you run cucumber with Scala 2.11 and sbt 0.
- ruby - simplify string multiply concatenation
- GRPC: make high-throughput client in Java/Scala
- Setting up multiple test folders in a SBT project
- Testing request with CSRF Token in Play framework
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 specialStringBuilder
class in Scala, that "provides an API compatible withjava.lang.StringBuilder
"; see http://www.scala-lang.org/api/2.7.5/scala/StringBuilder.html.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 thats += "foo"
is equivalent tos = s + "foo"
(i.e. it creates a newString
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 aStringBuilder
instead of aString
. Usually the difference is not important. (Of course, "simple, clear code" is slightly contradictory: using+=
is simpler, usingStringBuilder
is clearer. But still, the decision should usually be based on code-writing considerations rather than minor performance considerations.)Scala uses
java.lang.String
as the type for strings, so it is subject to the same characteristics.I want to add: if you have a sequence of strings, then there is already a method to create a new string out of them (all items, concatenated). It's called
mkString
.Example: (http://ideone.com/QJhkAG)
Scalas String concatenation works the same way as Javas does.
is translated to
StringBuilder is scala.collection.mutable.StringBuilder. That's the reason why the value appended to the StringBuilder is boxed by the compiler.
You can check the behavior by decompile the bytecode with javap.