Scala 2.8的for表達式:性能與運行順序的改進
本文來自EastSun的博客,原文標題為《Scala2.8探秘之for表達式》。
51CTO編輯推薦:Scala編程語言專題
雖然Scala2.8還在持續跳票中,但目前Nightly Build版本的可用性已經很高了,其中Scala2.8中主要特性都已經實現。毫無疑問,Scala2.8的發布將會是Scala發展中的一個重大里程碑。在這個版本中,不僅包括了許多Scala社區期待已久的特性,如命名參數、類型特殊化等等,詳細的信息可以參看http://eastsun.javaeye.com/blog/373710;而且包含了一些對之前Scala中設計不合理的地方的改進,例如Scala中對String以及數組的處理,在之前的版本中Scala編譯器在編譯的時候對這兩種類型進行了一些比較特殊(魔法)的處理,這樣做雖然某些程度上使得這兩種類型在Scala中更加易用,但同時也破壞了Scala中的一致性,并隨之產生了一些離奇的問題。舉個例子,在Scala2.7.7 final中我們可以看到如下結果:
- //Scala2.7.7 final
- scala> val array = Array("String Array")
- array: Array[java.lang.String] = Array(String Array)
- scala> println(array.toString())
- Array(String Array)
- scala> println(array)
- [Ljava.lang.String;@139491b
- scala> "WOW" == "WOW".reverse
- res4: Boolean = false
- scala> "abcdefg" map { _.toUpperCase }
- res5: Seq[Char] = ArrayBufferRO(A, B, C, D, E, F, G) //注意,得到的是個Seq[Char]而不是String
顯然這樣的運行結果有違我們的直覺,即使是對Scala有一定了解的人也未必能馬上明白其中的奧妙。
在Scala2.8中,這些問題都得到了一定的解決——可能有些解決方式會讓你覺得退步了,但是保持了Scala的一致性,并且消除了編譯器在背后做的那些魔法,使事情變得簡單——雖然這樣破壞了Scala的向后兼容性,但我認為這樣做事非常值得的:這為Scala成為一門成功的語言墊下了基礎。下面我們看看在Scala 2.8.0.r20117-b20091213020323中上面代碼的運行結果:
- scala> val array = Array("String Array")
- array: Array[java.lang.String] = Array(String Array)
- scala> println(array.toString())
- [Ljava.lang.String;@335053
- scala> println(array)
- [Ljava.lang.String;@335053
- scala> "WOW" == "WOW".reverse
- res2: Boolean = true
- scala> "abcdefg" map { _.toUpperCase }
- res3: String = ABCDEFG
可以看到,運行結果就如我們所預想的那樣——固然其中數組的toString結果變得丑陋了,和Java中一樣丑陋,但保持一致了。
OK,String與數組的討論就此為止,以后如果有時間我再來詳細解釋一下其背后的故事;現在我們轉向本文要討論的東東:Scala中的for表達式。注意:在本文中使用了兩種不同的Scala版本:Scala2.7.7final與2.8.0.r20117-b20091213020323進行對比。
1.Scala2.8之前的for表達式
在Scala中,通常有以下幾種使用方式:
- for (p <- e) e'
- for (p <- e if g) e'
- for (p <- e; p' <- e' ...) e''
以及相應的
- for (p <- e) yield e'
- for (p <- e if g) yield e'
- for (p <- e; p' <- e' ...) yield e''
其中p,p'為Scala中的Pattern;e,e',e''為表達式;g為Boolean表達式。
根據《The Scala Language Specification Version 2.7》,上面的for表達式將在編譯階段展開為下面的形式(沒有考慮p為比較復雜的Pattern時的情形):
- for (p <- e) e' => e.foreach { case p => e' }
- for (p <- e if g) e' => for (p <- e.filter{ (x1,...,xn) => g }) e' => ..
- for (p <- e; p' <- e' ...) e'' => e.foreach{ case p => for (p' <- e' ...) e'' }
以及相應的
- for (p <- e) yield e' => e.map { case p => e' }
- for (p <- e if g) yield e' => for (p <- e.filter{ (x1,...,xn) => g }) yield e'
- for (p <- e; p' <- e' ...) yield e'' => e.flatmap { case p => for (p' <- e' ...) yield e'' }
注意的是,這個轉換發生在類型檢查之前。也就是說,對map,filter,flatMap以及foreach這四個方法的方法簽名沒有任何其它限制,只需要滿足展開后for語句的類型檢查。通常情況下,對于一個具有類型參數A的類C——一般表示某種數據結構(集合)——下面的定義方式是比較自然的:
- class C[A] {
- def map[B](f: A => B): C[B]
- def flatMap[B](f: A => C[B]): C[B]
- def filter(p: A => Boolean): C[A]
- def foreach(b: A => Unit): Unit
- }
相對Java1.5中的for語句,Scala的實現更加靈活,并且以一種輕量級的方式實現了List comprehension。舉個例子,下面幾行代碼實現了求一個List的全排列:
- scala> def perm[T](ls: List[T]): List[List[T]] = ls match {
- | case Nil => List(Nil)
- | case xs => for(x <- xs;ys <- perm(xs-x)) yield x::ys
- | }
- perm: [T](List[T])List[List[T]]
- scala> perm(1::2::3::Nil)
- res2: List[List[Int]] = List(List(1, 2, 3), List(1, 3, 2), List(2, 1, 3),
- List(2, 3, 1), List(3, 1, 2), List(3, 2, 1))
但是這個轉換規則還不甚完美。當轉換后的表達式含有filter方法的時候,會產生幾個問題。
(a)性能問題
以一個簡單的問題為例:求1~999中所有偶數之和。
下面是兩段類似的解決代碼:
- val set = 1 until 1000
- var sum = 0
- for(num <- set;if(num%2 == 0)) sum += num
或者把if語句移到括號外面:
- val set = 1 until 1000
- var sum = 0
- for(num <- set) if(num%2 == 0) sum += num
這兩段代碼功能上應該是等價的,但是運行效率如何呢?下面首先寫一個粗略的測試函數:
- /**
- 計算count次調用call所需的時間,單位:毫秒
- */
- def time(call : => Unit,count: Int): Long = {
- var cnt = count
- val start = System.currentTimeMillis
- while(cnt > 0) {
- call
- cnt -= 1
- }
- System.currentTimeMillis - start
- }
先在Scala2.7.7final中將每段代碼各運行十萬次:
- scala> val set = 1 until 1000
- set: Range = Range(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, ...
- scala> time({
- | var sum = 0
- | for(num <- set;if(num%2 == 0)) sum += num
- | },100000)
- res3: Long = 47390
- scala>
- scala> time({
- | var sum = 0
- | for(num <- set) if(num%2 == 0) sum += num
- | },100000)
- res4: Long = 3344
- scala>
測試結果很出乎意料:兩段類似的代碼,性能竟相差一個數量級!
之所以會有這么大的差異,根據上述的轉換規則,第一段代碼將會轉換為下面的實際執行代碼:
- val set = 1 until 1000
- var sum = 0
- set.filter{ num => num%2 == 0) }.foreach{ case num => sum += num }
而第二段代碼實際執行的是:
- val set = 1 until 1000
- var sum = 0
- set.foreach{ case num => if(num%2 == 0) sum += num }
相對而言,第一段代碼會調用filter方法,創建一個新的集合類,而這個集合類包含了1~999中所有的偶數。顯然這個過程是比較昂貴的,也是不必要的。
(b)運行順序
以
- for (p <- e if g) e'
為例,實際運行的代碼為:
- e.filter{ (x1,...,xn) => g }.foreach{ case p => e'}
可以看到,雖然直觀上if g與e'在遍歷的時候應該是依次循環執行;但事實上轉換后if g整體先于e'執行。當g與e'中同時包含一個變量v,并且在g中對變量v進行改動時,實際運行結果可能和我們所預想的不一致。可能問題描述的不是很清楚,下面引用fineqtbull同學在for語句中內嵌if語句的副作用一文中的代碼作為例子來說明:實現compress方法,其功能是將一個list中連續相同的元素刪減至一個。比如compress(List(1,1,2,3,3,1,1,4)) == List(1,2,3,1,4),下面是兩段類似的實現代碼,咋一看都沒問題,但運行結果卻不一樣。
- Welcome to Scala version 2.7.7.final (Java HotSpot(TM) Client VM, Java 1.6.0_17).
- scala> def compress1[T](ls: List[T]): List[T] = {
- | var res = List(ls.first)
- | for(x <- ls) if(x != res.last) res = res:::List(x)
- | res
- | }
- compress1: [T](List[T])List[T]
- scala> def compress2[T](ls: List[T]): List[T] = {
- | var res = List(ls.first)
- | for(x <- ls;if(x != res.last)) res = res:::List(x)
- | res
- | }
- compress2: [T](List[T])List[T]
- scala> compress1(List(1,1,2,3,3,1,1,4))
- res0: List[Int] = List(1, 2, 3, 1, 4)
- scala> compress2(List(1,1,2,3,3,1,1,4))
- res1: List[Int] = List(1, 2, 3, 3, 4)
- scala>
有了之前的說明,我們不難發現其原因所在。但這樣的結果顯然違反了C/Java中習慣用法,很容易讓一個剛接觸Scala的人產生困惑。
2.Scala2.8中的for表達式
剛才已經提到了Scala2.8之前for表達式所存在的兩個問題,那么在Scala2.8中這兩個問題有沒有得到解決呢?下面將之前的代碼在2.8.0.r20117-b20091213020323重新運行一次試試:
- Welcome to Scala version 2.8.0.r20117-b20091213020323 (Java HotSpot(TM) Client VM, Java 1.6.0_17).
- scala> def time(call : => Unit,count: Int): Long = {
- | var cnt = count
- | val start = System.currentTimeMillis
- | while(cnt > 0) {
- | call
- | cnt -= 1
- | }
- | System.currentTimeMillis - start
- | }
- time: (call: => Unit,count: Int)Long
- scala> val set = 1 until 1000
- set: scala.collection.immutable.Range ...
- scala> time({
- | var sum = 0
- | for(num <- set;if(num%2 == 0)) sum += num
- | },100000)
- res0: Long = 6906
- scala> time({
- | var sum = 0
- | for(num <- set) if(num%2 == 0) sum += num
- | },100000)
- res1: Long = 4312
- scala> def compress1[T](ls: List[T]): List[T] = {
- | var res = List(ls.first)
- | for(x <- ls) if(x != res.last) res = res:::List(x)
- | res
- | }
- compress1: [T](ls: List[T])List[T]
- scala> def compress2[T](ls: List[T]): List[T] = {
- | var res = List(ls.first)
- | for(x <- ls;if(x != res.last)) res = res:::List(x)
- | res
- | }
- compress2: [T](ls: List[T])List[T]
- scala> compress1(List(1,1,2,3,3,1,1,4))
- res2: List[Int] = List(1, 2, 3, 1, 4)
- scala> compress2(List(1,1,2,3,3,1,1,4))
- res3: List[Int] = List(1, 2, 3, 1, 4)
- scala>
#T#可以看到Scala2.8中已經很好的解決了這兩個問題。對于一門語言,要想對已經存在的問題進行改進是很困難的,因為首先這些改進要盡可能少的影響已經存在的舊有代碼,另一方面不能帶來新的問題。幸運的是,Martin想到了一個簡單而優雅的方法成功做到了這些。下面簡單的敘述一下Martin的解決方法,感興趣的同學可以去看Martin的原文Rethinking filter。
首先,Martin引入了一個新的方法withFilter,這個方法與filter方法一樣以一個條件函數A => Boolean作為參數。與filter方法不同的是,withFilter方法是lazy的。它并不會創建一個新的包含符合條件的元素所組成的集合類,而是返回一個代理類WithFilter,這個類具有foreach、map、flatMap以及withFilter等方法,并且所有這些方法的調用是與原來條件組合的結果。下面是TraversableLike中WithFilter的實現,Scala2.8中所有的集合類都繼承了TraversableLike:
- class WithFilter(p: A => Boolean) {
- /** Builds a new collection by applying a function to all elements of the
- * outer $coll containing this `WithFilter` instance that satisfy predicate `p`.
- *
- * @param f the function to apply to each element.
- * @tparam B the element type of the returned collection.
- * @tparam That $thatinfo
- * @param bf $bfinfo
- * @return a new collection of type `That` resulting from applying the given function
- * `f` to each element of the outer $coll that satisfies predicate `p`
- * and collecting the results.
- *
- * @usecase def map[B](f: A => B): $Coll[B]
- *
- * @return a new $coll resulting from applying the given function
- * `f` to each element of the outer $coll that satisfies predicate `p`
- * and collecting the results.
- */
- def map[B, That](f: A => B)(implicit bf: CanBuildFrom[Repr, B, That]): That = {
- val b = bf(repr)
- for (x <- self)
- if (p(x)) b += f(x)
- b.result
- }
- /** Builds a new collection by applying a function to all elements of the
- * outer $coll containing this `WithFilter` instance that satisfy predicate `p` and concatenating the results.
- *
- * @param f the function to apply to each element.
- * @tparam B the element type of the returned collection.
- * @tparam That $thatinfo
- * @param bf $bfinfo
- * @return a new collection of type `That` resulting from applying the given collection-valued function
- * `f` to each element of the outer $coll that satisfies predicate `p` and concatenating the results.
- *
- * @usecase def flatMap[B](f: A => Traversable[B]): $Coll[B]
- *
- * @return a new $coll resulting from applying the given collection-valued function
- * `f` to each element of the outer $coll that satisfies predicate `p` and concatenating the results.
- */
- def flatMap[B, That](f: A => Traversable[B])(implicit bf: CanBuildFrom[Repr, B, That]): That = {
- val b = bf(repr)
- for (x <- self)
- if (p(x)) b ++= f(x)
- b.result
- }
- /** Applies a function `f` to all elements of the outer $coll containing this `WithFilter` instance
- * that satisfy predicate `p`.
- *
- * @param f the function that is applied for its side-effect to every element.
- * The result of function `f` is discarded.
- *
- * @tparam U the type parameter describing the result of function `f`.
- * This result will always be ignored. Typically `U` is `Unit`,
- * but this is not necessary.
- *
- * @usecase def foreach(f: A => Unit): Unit
- */
- def foreach[U](f: A => U): Unit =
- for (x <- self)
- if (p(x)) f(x)
- /** Further refines the filter for this $coll.
- *
- * @param q the predicate used to test elements.
- * @return an object of class `WithFilter`, which supports
- * `map`, `flatMap`, `foreach`, and `withFilter` operations.
- * All these operations apply to those elements of this $coll which
- * satify the predicate `q` in addition to the predicate `p`.
- */
- def withFilter(q: A => Boolean): WithFilter =
- new WithFilter(x => p(x) && q(x))
- }
在Scala2.8中,for表達式的轉換方式大體保持不變,只是將以前使用filter的地方全部替換為withFilter方法。
結語:可以看到Scala2.8成功解決了之前Scala中存在的一些問題,使得Scala語言變得更加優雅、強大。你還在等待Java7的閉包嗎?趕緊去嘗試Scala2.8吧^_^