Fastring is a string formatting library for Scala.
Fastring is also designed to be a template engine,
and it is an excellent replacement of JSP, Scalate or FreeMarker.
Fastring uses string interpolation syntax.
For example, if you are writing a CGI page:
import com.dongxiguo.fastring.Fastring.Implicits._
def printHtml(link: java.net.URL) {
val fastHtml = fast"<html><body><a href='$link'>Click Me!</a></body></html>"
print(fastHtml)
}
I made a benchmark. I used 4 different ways to create a 545-characters string.
- Fastring (
fast"Concat with $something"syntax); - String concatenation (
s"Concat with $something"syntax); - Handwritten
StringBuilder(stringBuilder ++= "Build from " ++= somethingsyntax); java.util.Formatter(f"Format with $something"syntax).
This is the result from my Intel i5-3450 computer:
| Fastring |
|
Took 669 nanoseconds to generate a 545-characters string. (Simple and fast) |
|---|---|---|
| String concatenation |
|
Took 1738 nanoseconds to generate a 545-characters string. (Simple but slow) |
Handwritten StringBuilder
|
|
Took 537 nanoseconds to generate a 545-characters string. (Fast but too trivial) |
java.util.Formatter
|
|
Took 7436 nanoseconds to generate a 545-characters string. (Simple but extremely slow) |
Fastring is so fast because it is lazily evaluated.
It avoids coping content for nested String Interpolation.
Thus, Fastring is very suitable to generate complex text content(e.g. HTML, JSON).
For example, in the previous benchmark for Fastring, the most of time was spent on invoking toString.
You can avoid these overhead if you do not need a whole string. For example:
// Faster than: print(fast"My lazy string from $something")
fast"My lazy string from $something".foreach(print)
You can invoke foreach because Fastring is just a Traversable[String].
There is a mkFastring method for Seq:
// Enable mkFastring method
import com.dongxiguo.fastring.Fastring.Implicits._
// Got Fastring("Seq.mkFastring: Hello, world")
fast"Seq.mkFastring: ${Seq("Hello", "world").mkFastring(", ")}"
// Also works, but slower:
// Got Fastring("Seq.mkString: Hello, world")
fast"Seq.mkString: ${Seq("Hello", "world").mkString(", ")}"
And a leftPad method for Byte, Short, Int and Long:
// Enable leftPad method
import com.dongxiguo.fastring.Fastring.Implicits._
// Got Fastring("Int.leftPad: 123")
fast"Int.leftPad: ${123.leftPad(5)}"
// Got Fastring("Int.leftPad: 00123")
fast"Int.leftPad: ${123.leftPad(5, '0')}"
Put these lines in your build.sbt if you use Sbt:
libraryDependencies += "com.dongxiguo" %% "fastring" % "latest.release"
See http://mvnrepository.com/artifact/com.dongxiguo/fastring_2.12 if you use Maven or other build systems.
Note that Fastring requires Scala 2.10, 2.11 or 2.12.