Created
September 1, 2010 17:07
-
-
Save mccv/561015 to your computer and use it in GitHub Desktop.
This file contains 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
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) | |
}} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Adding string builder benchmark