In Scala, is there a significant CPU or memory impact to using implicit type conversions to augment a class\'s functionality vs. other possible implementation choices?
I tried to setup a microbenchmark using the excellent Scala-Benchmark-Template.
It is very difficult to write a meaningful (non optimized away by the JIT) benchmark which tests just the implicit conversions, so I had to add a bit of overhead.
Here is the code:
class FunkyBench extends SimpleScalaBenchmark {
val N = 10000
def timeDirect( reps: Int ) = repeat(reps) {
var strs = List[String]()
var s = "a"
for( i <- 0 until N ) {
s += "a"
strs ::= "Funky " + s
}
strs
}
def timeImplicit( reps: Int ) = repeat(reps) {
import Funky._
var strs = List[String]()
var s = "a"
for( i <- 0 until N ) {
s += "a"
strs ::= s.funkify
}
strs
}
}
And here are the results:
[info] benchmark ms linear runtime
[info] Direct 308 =============================
[info] Implicit 309 ==============================
My conclusion: in any non trivial piece of code, the impact of implicit conversions (object creation) is not measurable.
EDIT: I used scala 2.9.0 and java 1.6.0_24 (in server mode)