Skip to content

Instantly share code, notes, and snippets.

@bdkosher
Created April 10, 2017 20:56
Show Gist options
  • Save bdkosher/529fb04b8fbb1d165d9c90a77ce6f119 to your computer and use it in GitHub Desktop.
Save bdkosher/529fb04b8fbb1d165d9c90a77ce6f119 to your computer and use it in GitHub Desktop.
Math with numbers is faster than math with Strings
def mathWithNumbers(String str) {
double secondsPlusRemainder = Double.valueOf(str)
long seconds = (long) Math.floor(secondsPlusRemainder);
long nanoSeconds = ((secondsPlusRemainder - seconds) * 1_000_000_000) as long
[seconds, nanoSeconds]
}
def mathWithStrings(String str) {
def (left, right) = str.split(/\./)
long seconds = left as long
long nanoSeconds = right.padRight(9, '0') as long
[seconds, nanoSeconds]
}
def timeIt = { resultFormatter = { obj -> obj?.toString() }, closure ->
def start = System.nanoTime()
def result = null
try {
result = closure()
} catch (Exception e) {
result = e
}
def end = System.nanoTime()
def ms = (end - start) / 1e6
if (resultFormatter) {
println "Result ${resultFormatter(result)} obtained in $ms ms"
}
[result, ms]
}
int limit = 10_000_000
timeIt {
new Random(42).doubles(0.0d, 60.0d).limit(limit).each { d ->
String str = Double.toString(d)[0..8]
mathWithStrings(str)
}
}
timeIt {
new Random(42).doubles(0.0d, 60.0d).limit(limit).each { d ->
String str = Double.toString(d)[0..8]
mathWithNumbers(str)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment