circeのsemiautoでEncoderとDecoderそれぞれ定義とCodecのみ定義でのcompile時間比較

最初に結論を書いておくと、Scala 2.13でもScala 3でも、Codec定義の方が少し速かったです。

以下、ベンチマーク用のコードや結果を雑に貼り付けていく

ベンチマーク用コードなど

build.sbt

val common = Def.settings(
  scalaVersion := "2.13.14",
  libraryDependencies += "io.circe" %% "circe-generic" % "0.14.9",
  scalacOptions ++= Seq("-feature", "-deprecation"),
)

def genSource(genCode: Int => String): Def.SettingsDefinition = Def.settings(
  Compile / sourceGenerators += task {
    val dir = (Compile / sourceManaged).value
    val f = dir / "Main.scala"
    val body = (1 to 1000).map(genCode).mkString("\n", "\n", "\n")
    val src =
      s"""|package example
          |
          |import io.circe.generic.semiauto._
          |import io.circe.Encoder
          |import io.circe.Decoder
          |import io.circe.Codec
          |
          |object Main {
          |$body
          |}
          |""".stripMargin
    IO.write(f, src)
    Seq(f)
  }
)

val a1 = project.settings(common)

val profileTrace = {
  scalacOptions ++= {
    if (scalaBinaryVersion.value == "2.13") {
      Seq("-Yprofile-trace", s"${name.value}.json")
    } else {
      Nil
    }
  }
}


val codec = project
  .settings(
    common,
    profileTrace,
    genSource { n =>
      s"def x${n}: Codec[A] = deriveCodec[A]"
    },
  )
  .dependsOn(a1)

val encoder_decoder = project
  .settings(
    common,
    profileTrace,
    genSource { n =>
      Seq(
        s"def x${n}: Encoder[A] = deriveEncoder[A]",
        s"def y${n}: Decoder[A] = deriveDecoder[A]"
      ).mkString("\n")
    },
  )
  .dependsOn(a1)

a1/A.scala

package example

case class A(
  x1: Int,
  x2: String,
  x3: Option[Boolean],
  x4: List[Long]
)

sbtで a1/compile;codec/sources;codec/compile;encoder_decoder/sources;encoder_decoder/compile を2.13.14と3.5.0-RC3でそれぞれ多少繰り返して実施

Scala 2.13

  • codecのみ: 21秒
  • encoderとdecoder別々: 33秒

encoderとdecoder別々拡大図

encoderとdecoder別々全体図

codec拡大図

codec全体図

Scala 3.5.0=RC3

  • codecのみ: 8秒
  • encoderとdecoder別々: 9秒

circe特有なのかScala 2.13と3全般的な違いなのか謎だけどScala 3が2.13より数倍速いの何???