Created
March 14, 2017 08:56
-
-
Save alexandru/76af60367877615dfc5a234e78a3d1f6 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
import java.util.concurrent.TimeUnit | |
import org.openjdk.jmh.annotations._ | |
import scala.util.Random | |
@State(Scope.Thread) | |
@BenchmarkMode(Array(Mode.Throughput)) | |
@OutputTimeUnit(TimeUnit.SECONDS) | |
class IteratorBenchmark { | |
@Param(Array("8")) | |
var cycles = 0 | |
@Param(Array("8192")) | |
var size = 0 | |
var arrayRef: Array[Int] = null | |
var listRef: List[Int] = null | |
@Setup | |
def setup(): Unit = { | |
arrayRef = (0 until size).map(_ => Random.nextInt()).toArray | |
listRef = (0 until size).map(_ => Random.nextInt()).toList | |
} | |
@Benchmark | |
def array: Option[Long] = { | |
var sum = 0 | |
var cycle = 0 | |
while (cycle < cycles) { | |
var idx = 0 | |
while (idx < arrayRef.length) { | |
sum += arrayRef(idx) | |
idx += 1 | |
} | |
cycle += 1 | |
} | |
Option(sum) | |
} | |
@Benchmark | |
def arrayIter: Option[Long] = { | |
var sum = 0 | |
var cycle = 0 | |
while (cycle < cycles) { | |
val cursor = arrayRef.iterator | |
while (cursor.hasNext) sum += cursor.next() | |
cycle += 1 | |
} | |
Option(sum) | |
} | |
@Benchmark | |
def list: Option[Long] = { | |
var sum = 0 | |
var cycle = 0 | |
while (cycle < cycles) { | |
var cursor = listRef | |
while (cursor ne Nil) { | |
sum += cursor.head | |
cursor = cursor.tail | |
} | |
cycle += 1 | |
} | |
Option(sum) | |
} | |
@Benchmark | |
def listIter: Option[Long] = { | |
var sum = 0 | |
var cycle = 0 | |
while (cycle < cycles) { | |
val cursor = listRef.iterator | |
while (cursor.hasNext) sum += cursor.next() | |
cycle += 1 | |
} | |
Option(sum) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment