Last active
December 26, 2015 19:38
-
-
Save tstone/7202321 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
// reporting library | |
// http://stackoverflow.com/questions/9160001/how-to-profile-methods-in-scala | |
def perf[R](block: => R): Unit = { | |
val t0 = System.nanoTime() | |
block | |
val t1 = System.nanoTime() | |
val elapsed = (t1 - t0) / 1000000000f | |
println("Elapsed time: " + elapsed + "s") | |
} | |
// setup code | |
case class ValidatedPostalCode(code: String, plus4: Option[String] = None) { | |
val numericCode = code.toInt | |
require(numericCode > 0) | |
require(numericCode < 99999) | |
plus4.map { pf => | |
val numericPlus4 = pf.toInt | |
require(numericPlus4 > 0) | |
require(numericPlus4 < 9999) | |
} | |
override def toString = { | |
code + plus4.map(pf => "-" + pf).mkString | |
} | |
} | |
case class PostalCode(code: String, plus4: Option[String] = None) { | |
override def toString = { | |
code + plus4.map(pf => "-" + pf).mkString | |
} | |
} | |
// tests | |
def test1 = { | |
def doStuff(postalCode: String) = for(_ <- 1 to 1000000) "You live at " + postalCode | |
perf { | |
doStuff("12345-1234") | |
} | |
} | |
def test2 = { | |
def doStuff(postalCode: PostalCode) = for(_ <- 1 to 1000000) "You live at " + postalCode | |
perf{ | |
doStuff(new PostalCode("12345", Some("1234"))) | |
} | |
} | |
def test3 = { | |
def doStuff(postalCode: ValidatedPostalCode) = for(_ <- 1 to 1000000) "You live at " + postalCode | |
perf{ | |
doStuff(new ValidatedPostalCode("12345", Some("1234"))) | |
} | |
} | |
// run tests | |
test1 | |
test2 | |
test3 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment