Scala 2.8的for表达式:性能与运行顺序的改进

开发 后端
Scala 2.8将是Scala语言的一次重要更新,感兴趣的开发者们已经可以在通过其Nightly Build进行很好的体验(各个IDE也已经支持)。本文介绍了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中我们可以看到如下结果:

  1. //Scala2.7.7 final  
  2. scala> val array = Array("String Array")  
  3. array: Array[java.lang.String] = Array(String Array)  
  4.  
  5. scala> println(array.toString())  
  6. Array(String Array)  
  7.  
  8. scala> println(array)  
  9. [Ljava.lang.String;@139491b 
  10.  
  11. scala> "WOW" == "WOW".reverse  
  12. res4: Boolean = false 
  13.  
  14. scala> "abcdefg" map { _.toUpperCase }  
  15. res5: Seq[Char] = ArrayBufferRO(A, B, C, D, E, F, G)         //注意,得到的是个Seq[Char]而不是String  
  16.  

显然这样的运行结果有违我们的直觉,即使是对Scala有一定了解的人也未必能马上明白其中的奥妙。

在Scala2.8中,这些问题都得到了一定的解决——可能有些解决方式会让你觉得退步了,但是保持了Scala的一致性,并且消除了编译器在背后做的那些魔法,使事情变得简单——虽然这样破坏了Scala的向后兼容性,但我认为这样做事非常值得的:这为Scala成为一门成功的语言垫下了基础。下面我们看看在Scala 2.8.0.r20117-b20091213020323中上面代码的运行结果:

  1. scala> val array = Array("String Array")  
  2. array: Array[java.lang.String] = Array(String Array)  
  3.  
  4. scala> println(array.toString())  
  5. [Ljava.lang.String;@335053 
  6.  
  7. scala> println(array)  
  8. [Ljava.lang.String;@335053 
  9.  
  10. scala> "WOW" == "WOW".reverse  
  11. res2: Boolean = true 
  12.  
  13. scala> "abcdefg" map { _.toUpperCase }  
  14. res3: String = ABCDEFG  
  15.  

可以看到,运行结果就如我们所预想的那样——固然其中数组的toString结果变得丑陋了,和Java中一样丑陋,但保持一致了。

OK,String与数组的讨论就此为止,以后如果有时间我再来详细解释一下其背后的故事;现在我们转向本文要讨论的东东:Scala中的for表达式。注意:在本文中使用了两种不同的Scala版本:Scala2.7.7final与2.8.0.r20117-b20091213020323进行对比。

1.Scala2.8之前的for表达式

在Scala中,通常有以下几种使用方式:

  1. for (p <- e) e'  
  2. for (p <- e if g) e'  
  3. for (p <- e; p' <- e' ...) e'' 

以及相应的

  1. for (p <- e) yield e'  
  2. for (p <- e if g) yield e'  
  3. 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时的情形):

  1. for (p <- e) e'                 => e.foreach { case p => e' }  
  2. for (p <- e if g) e'            => for (p <- e.filter{ (x1,...,xn) => g }) e' => ..  
  3. for (p <- e; p' <- e' ...) e''  => e.foreach{ case p => for (p' <- e' ...) e'' }  

以及相应的

  1. for (p <- e) yield e'                => e.map { case p => e' }  
  2. for (p <- e if g) yield e'           => for (p <- e.filter{ (x1,...,xn) => g }) yield e' 
  3. for (p <- e; p' <- e' ...) yield e'' => e.flatmap { case p => for (p' <- e' ...) yield e'' }  

注意的是,这个转换发生在类型检查之前。也就是说,对map,filter,flatMap以及foreach这四个方法的方法签名没有任何其它限制,只需要满足展开后for语句的类型检查。通常情况下,对于一个具有类型参数A的类C——一般表示某种数据结构(集合)——下面的定义方式是比较自然的:

  1. class C[A] {  
  2.     def map[B](f: A => B): C[B]  
  3.     def flatMap[B](f: A => C[B]): C[B]  
  4.     def filter(p: A => Boolean): C[A]  
  5.     def foreach(b: A => Unit): Unit  
  6. }  
  7.  

相对Java1.5中的for语句,Scala的实现更加灵活,并且以一种轻量级的方式实现了List comprehension。举个例子,下面几行代码实现了求一个List的全排列:

  1. scala> def perm[T](ls: List[T]): List[List[T]] = ls match {  
  2.      |     case Nil => List(Nil)  
  3.      |     case xs  => for(x <- xs;ys <- perm(xs-x)) yield x::ys  
  4.      | }  
  5. perm: [T](List[T])List[List[T]]  
  6.  
  7. scala> perm(1::2::3::Nil)  
  8. res2: List[List[Int]] = List(List(123), List(132), List(213),  
  9.                              List(231), List(312), List(321))  
  10.  

但是这个转换规则还不甚完美。当转换后的表达式含有filter方法的时候,会产生几个问题。

(a)性能问题

以一个简单的问题为例:求1~999中所有偶数之和。

下面是两段类似的解决代码:

  1. val set = 1 until 1000 
  2. var sum = 0 
  3. for(num <- set;if(num%2 == 0)) sum += num  

或者把if语句移到括号外面:

  1. val set = 1 until 1000 
  2. var sum = 0 
  3. for(num <- set) if(num%2 == 0) sum += num  

这两段代码功能上应该是等价的,但是运行效率如何呢?下面首先写一个粗略的测试函数:

  1. /**  
  2.   计算count次调用call所需的时间,单位:毫秒  
  3. */ 
  4. def time(call : => Unit,count: Int): Long = {  
  5.     var cnt = count  
  6.     val start = System.currentTimeMillis  
  7.     while(cnt > 0) {  
  8.         call  
  9.         cnt -= 1 
  10.     }  
  11.     System.currentTimeMillis - start  
  12. }  
  13.  

先在Scala2.7.7final中将每段代码各运行十万次:

  1. scala> val set = 1 until 1000 
  2. set: Range = Range(12345678910, ...  
  3.  
  4. scala> time({  
  5.      |     var sum = 0 
  6.      |     for(num <- set;if(num%2 == 0)) sum += num  
  7.      | },100000)  
  8. res3: Long = 47390 
  9.  
  10. scala>  
  11.  
  12. scala> time({  
  13.      |     var sum = 0 
  14.      |     for(num <- set)  if(num%2 == 0) sum += num  
  15.      | },100000)  
  16. res4: Long = 3344 
  17.  
  18. scala>  
  19.  

测试结果很出乎意料:两段类似的代码,性能竟相差一个数量级!

之所以会有这么大的差异,根据上述的转换规则,第一段代码将会转换为下面的实际执行代码:

  1. val set = 1 until 1000 
  2. var sum = 0 
  3. set.filter{ num => num%2 == 0) }.foreach{ case num => sum += num }  

而第二段代码实际执行的是:

  1. val set = 1 until 1000 
  2. var sum = 0 
  3. set.foreach{ case num => if(num%2 == 0) sum += num }  

相对而言,第一段代码会调用filter方法,创建一个新的集合类,而这个集合类包含了1~999中所有的偶数。显然这个过程是比较昂贵的,也是不必要的。

(b)运行顺序

  1. for (p <- e if g) e'  
  2.  

为例,实际运行的代码为:

  1. e.filter{ (x1,...,xn) => g }.foreach{ case p => e'}  
  2.  

可以看到,虽然直观上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),下面是两段类似的实现代码,咋一看都没问题,但运行结果却不一样。

  1. Welcome to Scala version 2.7.7.final (Java HotSpot(TM) Client VM, Java 1.6.0_17).  
  2.  
  3. scala> def compress1[T](ls: List[T]): List[T] = {  
  4.      |     var res = List(ls.first)  
  5.      |     for(x <- ls) if(x != res.last) res = res:::List(x)  
  6.      |     res  
  7.      | }  
  8. compress1: [T](List[T])List[T]  
  9.  
  10. scala> def compress2[T](ls: List[T]): List[T] = {  
  11.      |     var res = List(ls.first)  
  12.      |     for(x <- ls;if(x != res.last)) res = res:::List(x)  
  13.      |     res  
  14.      | }  
  15. compress2: [T](List[T])List[T]  
  16.  
  17. scala> compress1(List(1,1,2,3,3,1,1,4))  
  18. res0: List[Int] = List(12314)  
  19.  
  20. scala> compress2(List(1,1,2,3,3,1,1,4))  
  21. res1: List[Int] = List(12334)  
  22.  
  23. scala>  
  24.  

有了之前的说明,我们不难发现其原因所在。但这样的结果显然违反了C/Java中习惯用法,很容易让一个刚接触Scala的人产生困惑。

2.Scala2.8中的for表达式

刚才已经提到了Scala2.8之前for表达式所存在的两个问题,那么在Scala2.8中这两个问题有没有得到解决呢?下面将之前的代码在2.8.0.r20117-b20091213020323重新运行一次试试:

  1. Welcome to Scala version 2.8.0.r20117-b20091213020323 (Java HotSpot(TM) Client VM, Java 1.6.0_17).  
  2.  
  3. scala> def time(call : => Unit,count: Int): Long = {  
  4.      |     var cnt = count  
  5.      |     val start = System.currentTimeMillis  
  6.      |     while(cnt > 0) {  
  7.      |         call  
  8.      |         cnt -= 1 
  9.      |     }  
  10.      |     System.currentTimeMillis - start  
  11.      | }  
  12. time: (call: => Unit,count: Int)Long  
  13.  
  14. scala> val set = 1 until 1000 
  15. set: scala.collection.immutable.Range ...  
  16.  
  17. scala> time({  
  18.      |     var sum = 0 
  19.      |     for(num <- set;if(num%2 == 0)) sum += num  
  20.      | },100000)  
  21. res0: Long = 6906 
  22.  
  23. scala> time({  
  24.      |     var sum = 0 
  25.      |     for(num <- set)  if(num%2 == 0) sum += num  
  26.      | },100000)  
  27. res1: Long = 4312 
  28.  
  29. scala> def compress1[T](ls: List[T]): List[T] = {  
  30.      |     var res = List(ls.first)  
  31.      |     for(x <- ls) if(x != res.last) res = res:::List(x)  
  32.      |     res  
  33.      | }  
  34. compress1: [T](ls: List[T])List[T]  
  35.  
  36. scala> def compress2[T](ls: List[T]): List[T] = {  
  37.      |     var res = List(ls.first)  
  38.      |     for(x <- ls;if(x != res.last)) res = res:::List(x)  
  39.      |     res  
  40.      | }  
  41. compress2: [T](ls: List[T])List[T]  
  42.  
  43. scala> compress1(List(1,1,2,3,3,1,1,4))  
  44. res2: List[Int] = List(12314)  
  45.  
  46. scala> compress2(List(1,1,2,3,3,1,1,4))  
  47. res3: List[Int] = List(12314)  
  48.  
  49. scala>  
  50.  

#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:

  1. class WithFilter(p: A => Boolean) {  
  2.  
  3.   /** Builds a new collection by applying a function to all elements of the  
  4.    *  outer $coll containing this `WithFilter` instance that satisfy predicate `p`.  
  5.    *  
  6.    *  @param f      the function to apply to each element.  
  7.    *  @tparam B     the element type of the returned collection.  
  8.    *  @tparam That  $thatinfo  
  9.    *  @param bf     $bfinfo  
  10.    *  @return       a new collection of type `That` resulting from applying the given function  
  11.    *                `f` to each element of the outer $coll that satisfies predicate `p`  
  12.    *                and collecting the results.  
  13.    *  
  14.    *  @usecase def map[B](f: A => B): $Coll[B]   
  15.    *    
  16.    *  @return       a new $coll resulting from applying the given function  
  17.    *                `f` to each element of the outer $coll that satisfies predicate `p`  
  18.    *                and collecting the results.  
  19.    */ 
  20.   def map[B, That](f: A => B)(implicit bf: CanBuildFrom[Repr, B, That]): That = {  
  21.     val b = bf(repr)  
  22.     for (x <- self)   
  23.       if (p(x)) b += f(x)  
  24.     b.result  
  25.   }  
  26.  
  27.   /** Builds a new collection by applying a function to all elements of the  
  28.    *  outer $coll containing this `WithFilter` instance that satisfy predicate `p` and concatenating the results.   
  29.    *  
  30.    *  @param f      the function to apply to each element.  
  31.    *  @tparam B     the element type of the returned collection.  
  32.    *  @tparam That  $thatinfo  
  33.    *  @param bf     $bfinfo  
  34.    *  @return       a new collection of type `That` resulting from applying the given collection-valued function  
  35.    *                `f` to each element of the outer $coll that satisfies predicate `p` and concatenating the results.  
  36.    *  
  37.    *  @usecase def flatMap[B](f: A => Traversable[B]): $Coll[B]  
  38.    *   
  39.    *  @return       a new $coll resulting from applying the given collection-valued function  
  40.    *                `f` to each element of the outer $coll that satisfies predicate `p` and concatenating the results.  
  41.    */ 
  42.   def flatMap[B, That](f: A => Traversable[B])(implicit bf: CanBuildFrom[Repr, B, That]): That = {  
  43.     val b = bf(repr)  
  44.     for (x <- self)   
  45.       if (p(x)) b ++= f(x)  
  46.     b.result  
  47.   }  
  48.  
  49.   /** Applies a function `f` to all elements of the outer $coll containing this `WithFilter` instance  
  50.    *  that satisfy predicate `p`.  
  51.    *  
  52.    *  @param  f   the function that is applied for its side-effect to every element.  
  53.    *              The result of function `f` is discarded.  
  54.    *                
  55.    *  @tparam  U  the type parameter describing the result of function `f`.   
  56.    *              This result will always be ignored. Typically `U` is `Unit`,  
  57.    *              but this is not necessary.  
  58.    *  
  59.    *  @usecase def foreach(f: A => Unit): Unit  
  60.    */     
  61.   def foreach[U](f: A => U): Unit =   
  62.     for (x <- self)   
  63.       if (p(x)) f(x)  
  64.  
  65.   /** Further refines the filter for this $coll.  
  66.    *  
  67.    *  @param q   the predicate used to test elements.  
  68.    *  @return    an object of class `WithFilter`, which supports  
  69.    *             `map`, `flatMap`, `foreach`, and `withFilter` operations.  
  70.    *             All these operations apply to those elements of this $coll which  
  71.    *             satify the predicate `q` in addition to the predicate `p`.  
  72.    */ 
  73.   def withFilter(q: A => Boolean): WithFilter =   
  74.     new WithFilter(x => p(x) && q(x))  
  75. }  

在Scala2.8中,for表达式的转换方式大体保持不变,只是将以前使用filter的地方全部替换为withFilter方法。

结语:可以看到Scala2.8成功解决了之前Scala中存在的一些问题,使得Scala语言变得更加优雅、强大。你还在等待Java7的闭包吗?赶紧去尝试Scala2.8吧^_^

责任编辑:yangsai 来源: JavaEye博客
相关推荐

2009-07-21 14:03:00

Scalaif表达式while循环

2009-07-21 14:38:08

Scalamatch表达式break和conti

2009-07-21 14:16:18

Scalafor表达式

2012-07-18 09:45:32

Java 8ScalaLambda

2021-05-25 09:18:04

正则表达式Linux字符串

2010-10-21 10:56:29

SQL Server查

2009-08-19 14:48:57

正则表达式性能

2009-08-10 16:57:21

Lambda表达式

2024-03-25 13:46:12

C#Lambda编程

2009-07-21 14:30:38

Scalatry-catch

2018-09-27 15:25:08

正则表达式前端

2014-01-05 17:41:09

PostgreSQL表达式

2012-06-26 10:03:58

JavaJava 8lambda

2024-01-04 08:25:03

String表达式工具

2009-08-07 14:24:31

.NET正则表达式

2024-03-13 13:09:14

性能智能座舱软件

2012-03-31 15:09:51

JavaFel

2012-01-12 10:21:57

正则表达式

2009-06-24 11:24:23

JavaScript验正则表达式

2009-09-08 09:32:13

正则表达式学习
点赞
收藏

51CTO技术栈公众号