I am trying to reverse a string containing unicode characters in Scala. I want to find the fastest way to do it. So far I have this code:
import scala.runtime.RichChar
def reverseInPlace(s: String): String = {
val reverse = new Array[RichChar](s.length)
for (i <- (0 to (s.length >> 1))) {
reverse(i) = s(s.length -i -1)
reverse(s.length -i -1) = s(i)
}
return reverse.mkString
}
def reverseLeft(s: String): String = s.foldLeft("") ( (a,b) =>
b + a
)
def reverseRight(s: String): String = s.foldRight("") ( (a,b) =>
b + a
)
def time[R](iterations:Int, block: => R) = {
val t0 = System.nanoTime()
for ( i <- 0 to iterations){
block // call-by-name
}
val t1 = System.nanoTime()
println("Elapsed time: " + (t1 - t0) + "ns")
}
time(1000, {
reverseRight("Hello\u0041")
})
time(1000, {
reverseInPlace("Hello\u0041")
})
time(1000, {
reverseLeft("Hello\u0041")
})
time(1000, {
"Hello\u0041".reverse
})
and on my macbook 2013 I get these results:
Elapsed time: 37013000ns
Elapsed time: 23592000ns
Elapsed time: 11647000ns
Elapsed time: 5579000ns
But I feel those numbers are bogus numbers. Who do I properly benchmark the functions using scala, sbt and the JMH library ?
Note: As pointed out from the comments, micro benchmarking in Java is a serious business See (How do I write a correct micro-benchmark in Java?) and https://groups.google.com/d/msg/mechanical-sympathy/m4opvy4xq3U/7lY8x8SvHgwJ. For why you shouldn't try to microbenchmark without using an external library.