Skip to content

Instantly share code, notes, and snippets.

@travisbrown
Last active August 15, 2016 15:21
Show Gist options
  • Save travisbrown/cf9697d33bd4ed8fa473ab46d4942e31 to your computer and use it in GitHub Desktop.
Save travisbrown/cf9697d33bd4ed8fa473ab46d4942e31 to your computer and use it in GitHub Desktop.
package cats.bench
import cats.data.Xor
import cats.instances.either._
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] = 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] = (ea |@| eb |@| ec).map(_ + _ + _)
@Benchmark def cartesianXor(): Xor[String, Int] = (xa |@| xb |@| xc).map(_ + _ + _)
}
@travisbrown
Copy link
Author

Throughput:

Benchmark                     Mode  Cnt         Score        Error  Units
EitherBench.cartesianEither  thrpt   40  23048770.345 ± 100760.617  ops/s
EitherBench.cartesianXor     thrpt   40  30149921.328 ± 150663.522  ops/s
EitherBench.flatMapsEither   thrpt   40  37727924.694 ± 176693.644  ops/s
EitherBench.flatMapsXor      thrpt   40  49800011.743 ± 197428.071  ops/s

And allocation rates:

Benchmark                                                     Mode  Cnt         Score         Error   Units
EitherBench.cartesianEither:gc.alloc.rate.norm               thrpt    5       240.000 ±       0.001    B/op
EitherBench.cartesianXor:gc.alloc.rate.norm                  thrpt    5       208.000 ±       0.001    B/op
EitherBench.flatMapsEither:gc.alloc.rate.norm                thrpt    5       136.000 ±       0.001    B/op
EitherBench.flatMapsXor:gc.alloc.rate.norm                   thrpt    5        80.000 ±       0.001    B/op

On:

cats(master)$ java -version
java version "1.8.0_92"
Java(TM) SE Runtime Environment (build 1.8.0_92-b14)
Java HotSpot(TM) 64-Bit Server VM (build 25.92-b14, mixed mode)

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