Skip to content

Instantly share code, notes, and snippets.

@nuttycom
Created October 8, 2012 22:20
Show Gist options
  • Save nuttycom/3855346 to your computer and use it in GitHub Desktop.
Save nuttycom/3855346 to your computer and use it in GitHub Desktop.
Simple switch/dispatch microbench
import scala.annotation.tailrec
sealed abstract class A {
def i: Int
}
object A {
@inline final def tpIdx(a: A) = a match {
case SA(_) => 0
case BA(_) => 1
case LA(_) => 2
case IA(_) => 3
case DA(_) => 4
}
def main(argv: Array[String]) = {
@tailrec def fill(arr: Array[A], i: Int): Array[A] = {
if (i < 0) arr else {
(i % 5) match {
case 0 => arr(i) = SA(i.toString)
case 1 => arr(i) = BA(i % 2 == 0)
case 2 => arr(i) = LA(i)
case 3 => arr(i) = IA(i)
case 4 => arr(i) = DA(i)
}
fill(arr, i - 1)
}
}
val samples = fill(new Array[A](1000000), 1000000 - 1)
val runs = 100
var i = 0
var acc = 0L
while (i < samples.length * runs) {
acc += tpIdx(samples(i % samples.length))
i += 1
}
println("warmup...." + acc)
val starttpi = System.currentTimeMillis
i = 0
acc = 0L
while (i < samples.length * runs) {
acc += tpIdx(samples(i % samples.length))
i += 1
}
val endtpi = System.currentTimeMillis
println("tpi: " + acc + " : " + (endtpi - starttpi))
i = 0
acc = 0L
while (i < samples.length * runs) {
acc += samples(i % samples.length).i
i += 1
}
println("warmup...." + acc)
val startdisp = System.currentTimeMillis
i = 0
acc = 0L
while (i < samples.length * runs) {
acc += samples(i % samples.length).i
i += 1
}
val enddisp = System.currentTimeMillis
println("disp: " + acc + " : " + (enddisp - startdisp))
}
}
case class SA(s: String) extends A {
final val i = 0
}
case class BA(b: Boolean) extends A {
final val i = 1
}
case class LA(l: Long) extends A {
final val i = 2
}
case class IA(i0: Int) extends A {
final val i = 3
}
case class DA(d: Double) extends A {
final val i = 4
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment