Last active
August 28, 2016 02:59
-
-
Save emesday/f1f920a267de34991714f789fe0b605b to your computer and use it in GitHub Desktop.
StringJoinBenchmark
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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