Skip to content

Instantly share code, notes, and snippets.

@emesday
Last active August 28, 2016 02:59
Show Gist options
  • Save emesday/f1f920a267de34991714f789fe0b605b to your computer and use it in GitHub Desktop.
Save emesday/f1f920a267de34991714f789fe0b605b to your computer and use it in GitHub Desktop.
StringJoinBenchmark
package w20160827
case class Log(s: String, l: Long, f: String, t: String, p: String) {
def usingFixedSize: String = {
// 23 = Long.MaxValue.toString.length + ("\t" * 4).length
val size = 23 + s.length + f.length + t.length + p.length
val sb = new StringBuilder(size, s)
sb append "\t"; sb append l
sb append "\t"; sb append f
sb append "\t"; sb append t
sb append "\t"; sb append p
sb.result()
}
def usingSeq: String = Seq(s, l, f, t, p).mkString("\t")
def usingProductIterator: String = productIterator.mkString("\t")
def usingInterpolation: String = s"$s\t$l\t$f\t$t\t$p"
def usingManipulation: String = s + "\t" + l + "\t" + f + "\t" + t + "\t" + p
}
object StringJoinBenchmark {
def run[T](n: Int)(f: => T): Unit = {
println(f)
val s = System.currentTimeMillis()
(0 until n).foreach { _ =>
f
}
println(System.currentTimeMillis() - s)
}
def main(args: Array[String]): Unit = {
val label = "label_name"
val ts = System.currentTimeMillis()
val from = "1234567890123456789"
val to = "1234567890123456789"
val props = """{"key1": "value1", "key2": "value2"}"""
run(1e8.toInt) {
Log(label, ts, from, to, props).usingFixedSize
}
run(1e8.toInt) {
Log(label, ts, from, to, props).usingManipulation
}
run(1e8.toInt) {
Log(label, ts, from, to, props).usingProductIterator
}
run(1e8.toInt) {
Log(label, ts, from, to, props).usingSeq
}
run(1e8.toInt) {
Log(label, ts, from, to, props).usingInterpolation
}
}
}
@emesday
Copy link
Author

emesday commented Aug 28, 2016

with Scala 2.10.6 & Java 1.8 on OSX(2.5 GHz, 16GB)

usingFixedSize: 14,875 ms
usingManipulation: 26,659 ms
usingProductIterator: 35,326 ms
usingSeq: 45,849 ms
usingInterpolation: 45,922ms

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment