spark——比較map和mapPartitions

Spark中,最基本的原則,就是每個task處理一個RDD的partition。


MapPartitions操作的優點:
如果是普通的map,比如一個partition中有1萬條數據;ok,那麼你的function要執行和計算1萬次。
但是,使用MapPartitions操作之後,一個task僅僅會執行一次function,function一次接收所有 的partition數
據。只要執行一次就可以了,性能比較高。
MapPartitions的缺點:可能會OOM
如果是普通的map操作,一次function的執行就處理一條數據;那麼如果內存不夠用的情況下, 比如處理了1千條
數據了,那麼這個時候內存不夠了,那麼就可以將已經處理完的1千條數據從 內存裏面垃圾回收掉,或者用其他方
法,騰出空間來。
所以說普通的map操作通常不會導致內存的OOM異常。
在項目中,自己先去估算一下RDD的數據量,以及每個partition的量,還有自己分配給每個executor 的內存資
源。看看一下子內存容納所有的partition數據,行不行。如果行,可以試一下,能跑通就好。 性能肯定是有提升
的。

//map和partition的區別:
scala> val rdd2 = rdd1.mapPartitions(_.map(_*10))
rdd2: org.apache.spark.rdd.RDD[Int] = MapPartitionsRDD[1] ...
scala> rdd2.collect
res1: Array[Int] = Array(10, 20, 30, 40, 50, 60, 70)
scala> rdd1.map(_ * 10).collect
res3: Array[Int] = Array(10, 20, 30, 40, 50, 60, 70)
介紹mapPartition和map的區別,引出下面的內容:
mapPartitionsWithIndex
val func = (index: Int, iter: Iterator[(Int)]) => {
iter.toList.map(x => "[partID:" + index + ", val: " + x + "]").iterator
}
val rdd1 = sc.parallelize(List(1,2,3,4,5,6,7,8,9), 2)
rdd1.mapPartitionsWithIndex(func).collect

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章