首页 > 其他 > 详细

Scala中ListBuffer高效遍历

时间:2015-08-19 07:05:33      阅读:187      评论:0      收藏:0      [点我收藏+]


package com.dt.scala.list


object ListBuffer_Internals {
  def main(args: Array[String]): Unit = {
    val list = List(1,2,3,4,5,6,7,8,9)
    increment(list)
    increment_MoreEffective(list)
    increment_MostEffective(list)
  }
  
  def increment(list :List[Int]) : List[Int] = list match {//函数建立堆栈需要消耗大量的内存
  case List() => List()
  case head :: tail => head + 1 :: increment(tail)
 }
  
  def increment_MoreEffective(list : List[Int]) : List[Int] = {//比上边那种有较少的内存消耗。理论上讲支持所有元素个数。但是这里会产生很多种中间结果的list对象,效率是非常低的。
    var result = List[Int]()
    for(element <- list) result = result ::: List(element + 1)
    result
  }
  
  def increment_MostEffective(list: List[Int]) : List[Int] = {//最高效、既能够使用循环遍历,又会避免创建那么多的中间对象,就引入了ListBuffer
    import scala.collection.mutable.ListBuffer  //可变
    var buffer = new ListBuffer[Int]
    for(element <- list) buffer += element + 1
    buffer.toList
  }
  
  //ListBuffer源码:
//  def += (x:A) : this.type = {
//    if (exported) copy()
//    if (start.isEmpty){
//      last0 = new :: (x,Nil)
//      start = last0
//    } else {
//      val last1 = last0
//      last0 = new :: (x,Nil)
//      last1.tl = last0   //不断在后边追加成员
//    }
//    len += 1
//    this
//  }
//  
//  override def toList:List[A] = {
//    exported = !start.isEmpty
//    start
//  }
}





版权声明:本文为博主原创文章,未经博主允许不得转载。

Scala中ListBuffer高效遍历

原文:http://blog.csdn.net/u013361361/article/details/47774505

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!