Skip to content

Instantly share code, notes, and snippets.

@shomah4a
Created July 20, 2020 04:07
Show Gist options
  • Save shomah4a/0f8cd88304f452570b4ef551ebfe6876 to your computer and use it in GitHub Desktop.
Save shomah4a/0f8cd88304f452570b4ef551ebfe6876 to your computer and use it in GitHub Desktop.
import arrow.core.Either
import arrow.core.extensions.fx
import arrow.core.flatMap
import java.lang.IllegalStateException
class Hello {
companion object {
@JvmStatic
fun main(args: Array<String>) {
val count = 100000
println("count = $count")
for (i in 1..10) {
check("when", count) {
byWhen { somefunc() }
}
check("flatmap", count) {
byFlatMap { somefunc() }
}
check("fx", count) {
byFx { somefunc() }
}
}
}
}
}
fun check(msg: String, count: Int, f: () -> Unit) {
val start = System.currentTimeMillis()
for (i in 1 .. count) {
f()
}
val end = System.currentTimeMillis()
println("$msg: ${end-start} millisec")
}
fun byWhen(f: () -> Either<Exception, String>): Either<Exception, String> {
val a = f()
return when(val a = f()) {
is Either.Right -> {
when (val b = f()) {
is Either.Right ->
Either.Right(a.b + b.b)
else -> Either.Left(IllegalStateException("hoge"))
}
}
else -> Either.Left(IllegalStateException("fuga"))
}
}
fun byFlatMap(f: () -> Either<Exception, String>): Either<Exception, String> {
return f().flatMap { a ->
f().map { b ->
a + b
}
}
}
fun byFx(f: () -> Either<Exception, String>): Either<Exception, String> {
return Either.fx<Exception, String> {
val a = f().bind()
val b = f().bind()
a + b
}
}
fun somefunc(): Either<Exception, String> =
Either.Right("aiueo")
fun somefunc2(): Either<Exception, String> =
Either.Left(IllegalStateException("fuga"))
@shomah4a
Copy link
Author

count = 100000
when: 76 millisec
flatmap: 92 millisec
fx: 1211 millisec
when: 6 millisec
flatmap: 5 millisec
fx: 586 millisec
when: 8 millisec
flatmap: 5 millisec
fx: 381 millisec
when: 8 millisec
flatmap: 5 millisec
fx: 411 millisec
when: 8 millisec
flatmap: 15 millisec
fx: 473 millisec
when: 10 millisec
flatmap: 8 millisec
fx: 543 millisec
when: 6 millisec
flatmap: 4 millisec
fx: 346 millisec
when: 5 millisec
flatmap: 4 millisec
fx: 366 millisec
when: 10 millisec
flatmap: 9 millisec
fx: 422 millisec
when: 5 millisec
flatmap: 4 millisec
fx: 314 millisec

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