From 1697132ec8e0df21c98a1420d186c58e02af69ab Mon Sep 17 00:00:00 2001 From: Paul Phillips Date: Fri, 30 Nov 2012 05:19:07 +0100 Subject: Eliminate allocations in Growable. --- src/library/scala/collection/generic/Growable.scala | 17 +++++++++++++++-- src/library/scala/collection/mutable/ListBuffer.scala | 15 --------------- 2 files changed, 15 insertions(+), 17 deletions(-) diff --git a/src/library/scala/collection/generic/Growable.scala b/src/library/scala/collection/generic/Growable.scala index cb75212e3d..52a0d32de1 100644 --- a/src/library/scala/collection/generic/Growable.scala +++ b/src/library/scala/collection/generic/Growable.scala @@ -6,10 +6,11 @@ ** |/ ** \* */ - package scala.collection package generic +import scala.annotation.tailrec + /** This trait forms part of collections that can be augmented * using a `+=` operator and that can be cleared of all elements using * a `clear` method. @@ -45,7 +46,19 @@ trait Growable[-A] extends Clearable { * @param xs the TraversableOnce producing the elements to $add. * @return the $coll itself. */ - def ++=(xs: TraversableOnce[A]): this.type = { xs.seq foreach += ; this } + def ++=(xs: TraversableOnce[A]): this.type = { + @tailrec def loop(xs: collection.LinearSeq[A]) { + if (xs.nonEmpty) { + this += xs.head + loop(xs.tail) + } + } + xs.seq match { + case xs: collection.LinearSeq[_] => loop(xs) + case xs => xs foreach += + } + this + } /** Clears the $coll's contents. After this operation, the * $coll is empty. diff --git a/src/library/scala/collection/mutable/ListBuffer.scala b/src/library/scala/collection/mutable/ListBuffer.scala index e059f31929..97d469bca2 100644 --- a/src/library/scala/collection/mutable/ListBuffer.scala +++ b/src/library/scala/collection/mutable/ListBuffer.scala @@ -6,12 +6,9 @@ ** |/ ** \* */ - - package scala.collection package mutable -import scala.annotation.tailrec import generic._ import immutable.{List, Nil, ::} import java.io._ @@ -179,20 +176,8 @@ final class ListBuffer[A] this } - private def ++=(elems: collection.LinearSeq[A]): this.type = { - @tailrec def loop(xs: collection.LinearSeq[A]) { - if (xs.nonEmpty) { - this += xs.head - loop(xs.tail) - } - } - loop(elems) - this - } - override def ++=(xs: TraversableOnce[A]): this.type = xs match { case x: AnyRef if x eq this => this ++= (this take size) - case xs: collection.LinearSeq[_] => this ++= xs case _ => super.++=(xs) } -- cgit v1.2.3