Skip to content

Instantly share code, notes, and snippets.

@rossabaker
Forked from travisbrown/EitherBench.scala
Last active August 9, 2016 01:02
Show Gist options
  • Save rossabaker/ae49d2716e47b2f2cb8542a6186dd638 to your computer and use it in GitHub Desktop.
Save rossabaker/ae49d2716e47b2f2cb8542a6186dd638 to your computer and use it in GitHub Desktop.
import cats.data.Xor
import cats.syntax.all._
import org.openjdk.jmh.annotations.{ Benchmark, Scope, State }
@State(Scope.Benchmark)
class EitherBench {
val ea: Either[String, Int] = Right(1)
val eb: Either[String, Int] = Right(2)
val ec: Either[String, Int] = Right(3)
val xa: Xor[String, Int] = Xor.right(1)
val xb: Xor[String, Int] = Xor.right(2)
val xc: Xor[String, Int] = Xor.right(3)
@Benchmark def flatMapsEither(): Either[String, Int] = {
import cats.implicits._
for {
a <- ea; b <- eb; c <- ec
} yield a + b + c
}
@Benchmark def flatMapsEitherSyntax(): Either[String, Int] = {
import EitherSyntax._
for {
a <- ea; b <- eb; c <- ec
} yield a + b + c
}
@Benchmark def flatMapsXor(): Xor[String, Int] = for {
a <- xa; b <- xb; c <- xc
} yield a + b + c
@Benchmark def cartesianEither(): Either[String, Int] = {
import cats.implicits._
(ea |@| eb |@| ec).map(_ + _ + _)
}
@Benchmark def cartesianEitherSyntax(): Either[String, Int] = {
import EitherSyntax._
for {
a <- ea; b <- eb; c <- ec
} yield a + b + c
}
@Benchmark def cartesianXor(): Xor[String, Int] = (xa |@| xb |@| xc).map(_ + _ + _)
}
object EitherSyntax {
implicit class EitherOps[A, B](val self: Either[A, B]) extends AnyVal {
def map[C](f: B => C) =
self match {
case Right(b) => Right(f(b))
case left @ Left(a) => left.asInstanceOf[Either[A, C]]
}
def flatMap[C](f: B => Either[A, C]) =
self match {
case Right(b) => f(b)
case left @ Left(a) => left.asInstanceOf[Either[A, C]]
}
}
}
@rossabaker
Copy link
Author

rossabaker commented Aug 9, 2016

jmh:run with default arguments:

[info] Benchmark                           Mode  Cnt         Score        Error  Units
[info] EitherBench.cartesianEither        thrpt  200  19839997.767 ±  97340.453  ops/s
[info] EitherBench.cartesianEitherSyntax  thrpt  200  70361484.969 ± 336307.506  ops/s
[info] EitherBench.cartesianXor           thrpt  200  26506086.351 ± 106640.262  ops/s
[info] EitherBench.flatMapsEither         thrpt  200  28634233.565 ± 202999.799  ops/s
[info] EitherBench.flatMapsEitherSyntax   thrpt  200  70627088.756 ± 328028.965  ops/s
[info] EitherBench.flatMapsXor            thrpt  200  71494999.826 ± 248440.207  ops/s

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment