今天在写spark代码时,遇到一个问题,在进行数据过滤时,总是特别的慢,后来分析了一下代码。
主业务逻辑就是用一个较小的文本数据过滤“大数据”,然后我用spark textFile进行加载然后collect形成一个集合,可能是java写多了,看到这个集合有contains方法,就使用了没有多想,然后就特别慢,排查代码发现,collect返回的是Array(scala中Array也有contains方法,这个被我忽略了),所以不用想导致很慢。下面是我做的是一个scala的性能统计的小实验,贴出来仅供参考。
val array = Array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
val set = Set(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
val hashSet = HashSet(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
val t1 = System.currentTimeMillis()
for (i <- 0 to 100000) array.contains(5)
val t2 = System.currentTimeMillis()
for (i <- 0 to 100000) set.contains(5)
val t3 = System.currentTimeMillis()
for (i <- 0 to 100000) hashSet.contains(5)
val t31 = System.currentTimeMillis()
println("Hit the target ---> Array time:" + (t2 - t1) + ", Set time : " + (t3 - t2)
+ ", HashSet time : " + (t31 - t3))
val t4 = System.currentTimeMillis()
for (i <- 0 to 100000) array.contains(11)
val t5 = System.currentTimeMillis()
for (6 <- 0 to 100000) set.contains(11)
val t6 = System.currentTimeMillis()
for (i <- 0 to 100000) hashSet.contains(5)
val t61 = System.currentTimeMillis()
println("NOT Hit the target ---> Array time:" + (t5 - t4) + ", Set time : " + (t6 -
t5)+ ", HashSet time : " + (t61 - t6))
}
结果如下:
Hit the target ---> Array time:32, Set time : 14, HashSet time : 7
NOT Hit the target ---> Array time:14, Set time : 6, HashSet time : 5
看到在10万次的比较下,各个集合的判断性能还是差别巨大,下次在用spark的时候要特别注意了!