-
-
Save rossabaker/ae49d2716e47b2f2cb8542a6186dd638 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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]] | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
jmh:run with default arguments: