Last active
March 25, 2019 23:52
-
-
Save shawjef3/3bce771eaaea57679461077df341b84f to your computer and use it in GitHub Desktop.
This file contains 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
package me.jeffshaw | |
import org.openjdk.jmh.annotations._ | |
import scala.annotation.tailrec | |
@State(Scope.Benchmark) | |
class CollectFirstBenchmarks { | |
val values = List.tabulate(1000)(identity) | |
def trivialPredicate(i: Int): Option[String] = { | |
None | |
} | |
def expensivePredicate(i: Int): Option[String] = { | |
List.tabulate(i)(Math.pow(_, 3)).find(_ == -1.0D).map(_.toString) | |
} | |
@tailrec | |
final def jimka[A, B](domain:List[A], f: A=>Option[B]): Option[B] = { | |
domain match { | |
case Nil => None | |
case d::tail => { | |
f(d) match { | |
case None => jimka(tail,f) | |
case found => found | |
} | |
} | |
} | |
} | |
def jducoeur[A, B](domain: List[A], f: A => Option[B]): Option[B] = { | |
domain.collectFirst(Function.unlift(f)) | |
} | |
@Benchmark | |
def benchmarkTrivialJimka(): Option[String] = { | |
jimka(values, trivialPredicate) | |
} | |
@Benchmark | |
def benchmarkTrivialJducoeur(): Option[String] = { | |
jducoeur(values, trivialPredicate) | |
} | |
@Benchmark | |
def benchmarkExpensiveJimka(): Option[String] = { | |
jimka(values, expensivePredicate) | |
} | |
@Benchmark | |
def benchmarkExpensiveJducoeur(): Option[String] = { | |
jducoeur(values, expensivePredicate) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment