Scala 2.10和2.9.2的性能比較
我已經(jīng)閱讀了 Scala 2.10.0-RC3 的一些新特性,該版本最值得關(guān)注的就是性能方面的提升,我很好奇這個提升的幅度到底有多大,于是我做了一個基準(zhǔn)測試。下面是我的兩個測試用的代碼:
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))
- }
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))
- }
其中 Sundaram 篩選方法運(yùn)行 120 次,查找小于 300 萬的所有素數(shù)。而 Eratosthenes 刷選方法運(yùn)行 60 次,查找小于 7萬5 的所有素數(shù),結(jié)果如下:
從上圖你可以看出,Sundaram 篩選方面的性能提升是微不足道的。而 Eratosthenes 篩選方法的性能提升達(dá)到了 2 倍之多。因?yàn)槲曳浅F诖?Scala 2.10 正式版的發(fā)布。
我的測試源碼在這里: https://github.com/markehammons/2.10.0-RC3-Benchmark
原文鏈接:markehammons