以下のStreamとlazyvalを使用して、lazysieveアルゴリズムの次の実装をコーディングしました。
def primes(): Stream[Int] = {
lazy val ps = 2 #:: sieve(3)
def sieve(p: Int): Stream[Int] = {
p #:: sieve(
Stream.from(p + 2, 2).
find(i=> ps.takeWhile(j => j * j <= i).
forall(i % _ > 0)).get)
}
ps
}
および(可変)ListBufferを使用した次の実装:
import scala.collection.mutable.ListBuffer
def primes(): Stream[Int] = {
def sieve(p: Int, ps: ListBuffer[Int]): Stream[Int] = {
p #:: { val nextprime =
Stream.from(p + 2, 2).
find(i=> ps.takeWhile(j => j * j <= i).
forall(i % _ > 0)).get
sieve(nextprime, ps += nextprime)
}
}
sieve(3, ListBuffer(3))}
primes()。takeWhile(_ <1000000).sizeを実行したとき、最初の実装は2番目の実装より3倍高速です。これの説明は何ですか?
2番目のバージョンを編集しました。sieve(3、ListBuffer())ではなくsieve(3、ListBuffer(3))である必要があります。