What is the performance impact of Scala implicit type conversions?

前端 未结 2 1321
囚心锁ツ
囚心锁ツ 2020-12-09 08:19

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?

相关标签:
2条回答
  • 2020-12-09 08:19

    JVM can optimize away the extra object allocations, if it detects that would be worthy.

    This is important, because if you just inline things you end up with bigger methods, which might cause performance problems with cache or even decrease the chance of JVM applying other optimizations.

    0 讨论(0)
  • 2020-12-09 08:45

    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)

    0 讨论(0)
提交回复
热议问题