Surrounding Scala Strings

If you do something in a single statement like "abc" + stringval + "abc", is that one immutable string copy, or two (noting that abc and 123 are constant at compile time)

Bonus round: would using a StringBuilder like the following have more or less overhead?

  def surround(s:String, ss:String):String = {
    val surrounded = new StringBuilder(s.length() + 2*ss.length(), s)
    surrounded.insert(0,ss)
    surrounded.append(ss)
    surrounded.mkString
  }

Or is there a more idiomatic way that I'm unaware of?

Answers


It has less overhead than concatenation. But the insert in your example is not efficient. The following is a little cleaner and uses only appends for efficiency.

def surround(s:String, ss:String) =
  new StringBuilder(s.length() + 2*ss.length(), ss).append(s).append(ss).mkString

Need Your Help

Synchronize Dataset - Multiple users, multiple timestamps

android ios dataset timestamp pandas

I'm trying to understand what is the best way to go about doing this:

Bind checkbox on DB initial null value

c# asp.net checkbox bind

I need to bind a checkBox but with this line of code,

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.