我已经阅读了 Scala 2.10.0-RC3 的一些新特性,该版本最值得关注的就是性能方面的提升,我很好奇这个提升的幅度到底有多大,于是我做了一个基准测试。下面是我的两个测试用的代码:
Eratosthenes 筛选
def eratosthenes(toNum: Int) = {
def sieveHelp(r: IndexedSeq[Int]): Stream[Int] = {
if(r.isEmpty)
Stream.empty
else
r.head #:: sieveHelp(r.tail.filterNot(_ % r.head == 0))
}
sieveHelp(2 +: (3 to toNum by 2))
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
Sundaram 筛选
def sundaram(toNum: Int) = {
val n = (toNum - 2)/2
val nonPrimes = for (i <- 1 to n; j <- i to (n - i) / (2 * i + 1)) yield i+j+(2*i*j)
2 +:((1 to n) diff nonPrimes map (2*_+1))
}
- 1.
- 2.
- 3.
- 4.
- 5.
其中 Sundaram 筛选方法运行 120 次,查找小于 300 万的所有素数。而 Eratosthenes 刷选方法运行 60 次,查找小于 7万5 的所有素数,结果如下:
从上图你可以看出,Sundaram 筛选方面的性能提升是微不足道的。而 Eratosthenes 筛选方法的性能提升达到了 2 倍之多。因为我非常期待 Scala 2.10 正式版的发布。
我的测试源码在这里: https://github.com/markehammons/2.10.0-RC3-Benchmark
原文链接:markehammons