Last active
August 29, 2015 14:11
-
-
Save voronaam/fbda8059a6aa36caa6ed 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
/** | |
* This is a benchmark to gauge if there is any performance hit into using Option.apply() in Scala. | |
* Use JMH to build it: http://blog.vorona.ca/measuring-scala-performance-with-jmh.html | |
*/ | |
package org.sample | |
import org.openjdk.jmh.annotations._ | |
import java.util.concurrent.TimeUnit | |
@Warmup(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS) | |
@Measurement(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS) | |
@Fork(3) | |
@State(Scope.Benchmark) | |
class MyBenchmark { | |
@Param(Array("4", "null")) | |
var strValue: String = _ | |
@Benchmark | |
def testOption(): Any = { | |
val value = if(strValue.equals("null")) null else java.lang.Long.valueOf(strValue) | |
Option(value).map(_ * 2).getOrElse(1L) | |
} | |
@Benchmark | |
def testNull(): Any = { | |
val value = if(strValue.equals("null")) null else java.lang.Long.valueOf(strValue) | |
if(value != null) value * 2 else 1L | |
} | |
} | |
/* Result: | |
Benchmark (strValue) Mode Samples Score Error Units | |
o.s.MyBenchmark.testNull 4 thrpt 15 84314649.298 ± 1203713.827 ops/s | |
o.s.MyBenchmark.testNull null thrpt 15 158563487.854 ± 2074024.325 ops/s | |
o.s.MyBenchmark.testOption 4 thrpt 15 83276054.167 ± 574030.725 ops/s | |
o.s.MyBenchmark.testOption null thrpt 15 165543753.295 ± 2113093.244 ops/s | |
* Conclusion: there is no performance impact | |
*/ | |
/* Another version to make sure we'd see the difference if there was one. | |
class MyBenchmark { | |
@Benchmark | |
def testOption(): Any = { | |
val value: java.lang.Long = 4L | |
Option(value).map(_ * 2).getOrElse(1L) | |
} | |
@Benchmark | |
def testNull(): Any = { | |
val value: java.lang.Long = 4L | |
if(value != null) value * 2 else 1L | |
} | |
@Benchmark | |
def testPlus(): Any = { | |
val value: java.lang.Long = 4L | |
if(value != null) (value + 1) * 2 else 1L | |
} | |
} | |
* It's results: | |
Benchmark Mode Samples Score Error Units | |
o.s.MyBenchmark.testNull thrpt 100 284044726.734 ± 11713071.741 ops/s | |
o.s.MyBenchmark.testOption thrpt 100 293796734.747 ± 9904997.303 ops/s | |
o.s.MyBenchmark.testPlus thrpt 100 261674420.570 ± 14340772.701 ops/s | |
* As you can see, one extra "plus" operation causes a noticeable drop in throughput. | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment