Skip to content

Instantly share code, notes, and snippets.

@mccv
Created September 1, 2010 17:07
Show Gist options
  • Save mccv/561015 to your computer and use it in GitHub Desktop.
Save mccv/561015 to your computer and use it in GitHub Desktop.
def timeLoops (loops: Int)(f: => Any) = {
val t1 = System.currentTimeMillis
for(i <- 1 to loops)
f
val elapsed = System.currentTimeMillis - t1
println("executed %d loops in %d ms, or %.2f loops/sec".format(
loops, elapsed, loops/(elapsed/1000.0)))
}
val loops = 1000000
val slices = Array("this has a string", "and another string")
val replacements = Array("string1", "string2")
val both = slices.zip(replacements)
val fmtString = slices.mkString(" (%s) ")
println("running %d loops of string format".format(loops))
timeLoops(loops) {
fmtString.format(replacements(0), replacements(1))
}
println("and again...")
println("running %d loops of string format".format(loops))
timeLoops(loops) {
fmtString.format(replacements(0), replacements(1))
}
println("running %d loops of string concat".format(loops))
timeLoops(loops) {
val sb = new StringBuffer()
both.foreach { case (slice, repl) => {
sb.append(slice)
sb.append(repl)
}}
}
println("and again...")
println("running %d loops of string concat".format(loops))
timeLoops(loops) {
val sb = new StringBuffer()
both.foreach { case (slice, repl) => {
sb.append(slice)
sb.append(repl)
}}
}
println("running %d loops of string concat w/ StringBuilder".format(loops))
timeLoops(loops) {
val sb = new StringBuilder()
both.foreach { case (slice, repl) => {
sb.append(slice)
sb.append(repl)
}}
}
println("and again...")
println("running %d loops of string concat w/ StringBuilder".format(loops))
timeLoops(loops) {
val sb = new StringBuilder()
both.foreach { case (slice, repl) => {
sb.append(slice)
sb.append(repl)
}}
}
@mccv
Copy link
Author

mccv commented Sep 1, 2010

Adding string builder benchmark

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