如何最有效地在Scala中合并和聚合2个地图?

时间:2018-08-31 17:50:26

标签: scala parallel-processing parallel-collections

我有以下2张地图:

val map12:Map[(String,String),Double]=Map(("Sam","0203") -> 16216.0, ("Jam","0157") -> 50756.0, ("Pam","0129") -> 3052.0)
val map22:Map[(String,String),Double]=Map(("Jam","0157") -> 16145.0, ("Pam","0129") -> 15258.0, ("Sam","0203") -> -1638.0, ("Dam","0088") -> -8440.0,("Ham","0104") -> 4130.0,("Hari","0268") -> -108.0, ("Om","0169") -> 5486.0, ("Shiv","0181") -> 275.0, ("Brahma","0148") -> 18739.0)

在第一种方法中,我使用foldLeft实现合并和累积:

val t1 = System.nanoTime()
val merged1 = (map12 foldLeft map22)((map22, map12) => map22 + (map12._1 -> (map12._2 + map22.getOrElse(map12._1, 0.0))))
val t2 = System.nanoTime()
println(" First Time taken :"+ (t2-t1))

在第二种方法中,我试图使用支持并行操作的aggregate()函数:

def merge(map12:Map[(String,String),Double], map22:Map[(String,String),Double]):Map[(String,String),Double]=
  map12 ++ map22.map{case(k, v) => k -> (v + (map12.getOrElse(k, 0.0)))}

val inArr= Array(map12,map22)

val t5 = System.nanoTime()
val mergedNew12 = inArr.par.aggregate(Map[(String,String),Double]())(merge,merge)
val t6 = System.nanoTime()
println(" Second Time taken :"+ (t6-t5))

但是我注意到foldLeft比聚合快得多。

我正在寻找有关如何使该操作最有效的建议。

1 个答案:

答案 0 :(得分:0)

如果希望通过运行par来提高聚合效率,请尝试使用Vector而不是Array,它是并行算法的最佳集合之一。

另一方面,并​​行工作会产生一些开销,因此,如果数据不足,将不方便。

根据您提供的数据,Vector.par.aggregate优于Array.par.aggregate,但是Vector.aggregate优于foldLeft。

val inVector= Vector(map12,map22)

val t7 = System.nanoTime()
val mergedNew12_2 = inVector.aggregate(Map[(String,String),Double]())(merge,merge)
val t8 = System.nanoTime()
println(" Third Time taken :"+ (t8-t7))

这是我的时代

First Time taken :6431723
Second Time taken:147474028
Third Time taken :4855489