使用并行集合,能够并行的访问集合,大幅提高性能。
举例:
1 val urls = List("http://scala-lang.org", 2 "https://github.com/yankay/scala-tour") 3 4 def fromURL(url: String) = scala.io.Source.fromURL(url) 5 .getLines().mkString("\n") 6 7 val t = System.currentTimeMillis() 8 urls.par.map(fromURL(_)) 9 println("time: " + (System.currentTimeMillis - t) + "ms")
使用方法,就只是把urls.map修改为urls.par.map。
再举之前wordCount的例子:
1 val file = List("warn 2013 msg", "warn 2012 msg", 2 "error 2013 msg", "warn 2013 msg") 3 4 def wordcount(str: String): Int = str.split(" ").count("msg" == _) 5 6 val num = file.par.map(wordcount).par.reduceLeft(_ + _) 7 8 println("wordcount:" + num)
在集合之前,使用前缀par.
时间: 2024-10-11 11:00:51