私の理解では、/: は foldLeft と同じであり、リストが「par」を使用して並列コレクションに変換される場合、集約は foldLeft のより高速なバージョンです。私が正しければ、次のコードが :/ と foldLeft がリストの「par」で使用される集計よりも高速であることを示しているのはなぜですか。
大きなリストの要素の合計と要素数を計算し、結果をタプル [Double,Double] に格納しています。
//initial tuple2 (sum,count)
val tsc:Tuple2[Double,Double] = Tuple2(0.0,0.0)
//create a large list
val largeList = List.tabulate(500000)(n=>n*n)
//note time
val time1 = System.currentTimeMillis
//using aggregate without par
largeList.aggregate(tsc) ((tsc,elem) => (tsc._1+elem, tsc._2+1), (tsc1, tsc2)=>((tsc1._1+tsc2._1), (tsc1._2+tsc2._2)))
//note time
val time2 = System.currentTimeMillis
//use aggregate with par
largeList.par.aggregate(tsc) ((tsc,elem) => (tsc._1+elem, tsc._2+1), (tsc1, tsc2)=>((tsc1._1+tsc2._1), (tsc1._2+tsc2._2)))
//note time
val time3 = System.currentTimeMillis
//use /:
(tsc /: largeList)((tsc,elem)=>(tsc._1+elem, tsc._2+1))
//note time
val time4 = System.currentTimeMillis
//use foldLeft
largeList.foldLeft(tsc)((tsc,elem)=>(tsc._1+elem, tsc._2+1))
//note time
val time5 = System.currentTimeMillis
//calcualte time difference
println ("Time without par (millisecond)"+(time2-time1))
println ("Time with par (millisecond)"+(time3-time2))
println ("Time with /: (millisecond)"+(time4-time3))
println ("Time with FoldLeft (millisecond)"+(time5-time4)
私は次の結果を得ました
1回目の実行結果
Time without par (millisecond)1198
Time with par (millisecond)1479
Time with /: (millisecond)626
Time with FoldLeft (millisecond)661
2回目の実行結果
Time without par (millisecond)703
Time with par (millisecond)581
Time with /: (millisecond)435
Time with FoldLeft (millisecond)423
cmdを使用してWindows 10でこれを実行しています。/: と FoldLeft はパフォーマンスが似ているように見え、aggregate よりもかなり優れています。実際、1 回目の実行では、par での集計の方が時間がかかりました。ウィンドウの「cmd」(コンソール)がマルチスレッドを活用できないことが原因で問題になる可能性があります(ここで推測するだけです)