Skip to content

Instantly share code, notes, and snippets.

@sargunv
Created January 27, 2016 05:20
Show Gist options
  • Save sargunv/9dcfd77861b194a6f071 to your computer and use it in GitHub Desktop.
Save sargunv/9dcfd77861b194a6f071 to your computer and use it in GitHub Desktop.
Kotlin sequence drop problem tester
import com.github.andrewoma.kommon.util.StopWatch
import java.util.concurrent.TimeUnit
class Squares(val length: Long): Iterable<Long>, Sequence<Long> {
override fun iterator() = object : Iterator<Long> {
var current: Long = 0
override fun hasNext() = current < length
override fun next() = Math.pow(current++.toDouble(), 2.toDouble()).toLong()
}
}
val sizes = listOf<Long>(100, 500, 1000, 1500)
fun test(name: String, block: ()->Unit) {
val sw = StopWatch();
sw.start()
block()
sw.stop()
println("${sw.toString(TimeUnit.MILLISECONDS)}\t$name")
}
fun main(vararg args: String) {
sizes.forEach { size ->
test("Iterable drop $size") {
var x: Iterable<Long> = Squares(size)
while (x.firstOrNull() != null)
x = x.drop(1)
}
test("Sequence drop $size") {
var x: Sequence<Long> = Squares(size)
while (x.firstOrNull() != null)
x = x.drop(1)
}
test("Sequence myDrop $size") {
var x: Sequence<Long> = Squares(size)
while (x.firstOrNull() != null)
x = x.myDrop(1)
}
println()
}
}
fun <T> Sequence<T>.myDrop(n: Int): Sequence<T> {
require(n >= 0) { "Requested element count $n is less than zero." }
return when {
n == 0 -> this
this is MyDropSequence -> MyDropSequence(this.sequence, this.count + n)
else -> MyDropSequence(this, n)
}
}
class MyDropSequence<T>(
val sequence: Sequence<T>,
val count: Int
): Sequence<T> {
init {
require(count >= 0) { throw IllegalArgumentException("count should be non-negative, but it is $count") }
}
override fun iterator(): Iterator<T> = object : Iterator<T> {
val iterator = sequence.iterator()
var left = count
private fun drop() {
while (left > 0 && iterator.hasNext()) {
iterator.next()
left--
}
}
override fun next(): T {
drop()
return iterator.next()
}
override fun hasNext(): Boolean {
drop()
return iterator.hasNext()
}
}
}
@sargunv
Copy link
Author

sargunv commented Jan 27, 2016

Sample output:

8.536 ms    Iterable drop 100
12.769 ms   Sequence drop 100
2.417 ms    Sequence myDrop 100

7.714 ms    Iterable drop 500
177.614 ms  Sequence drop 500
2.649 ms    Sequence myDrop 500

12.970 ms   Iterable drop 1000
1138.528 ms Sequence drop 1000
4.731 ms    Sequence myDrop 1000

4.439 ms    Iterable drop 1500
3801.664 ms Sequence drop 1500
3.861 ms    Sequence myDrop 1500

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment