diff options
Diffstat (limited to 'src/library/scala/collection/immutable/Range.scala')
-rw-r--r-- | src/library/scala/collection/immutable/Range.scala | 31 |
1 files changed, 14 insertions, 17 deletions
diff --git a/src/library/scala/collection/immutable/Range.scala b/src/library/scala/collection/immutable/Range.scala index 3ae8a2c342..ca6720da19 100644 --- a/src/library/scala/collection/immutable/Range.scala +++ b/src/library/scala/collection/immutable/Range.scala @@ -153,19 +153,15 @@ extends scala.collection.AbstractSeq[Int] } @inline final override def foreach[@specialized(Unit) U](f: Int => U) { - validateMaxLength() - val isCommonCase = (start != Int.MinValue || end != Int.MinValue) - var i = start - var count = 0 - val terminal = terminalElement - val step = this.step - while( - if(isCommonCase) { i != terminal } - else { count < numRangeElements } - ) { - f(i) - count += 1 - i += step + // Implementation chosen on the basis of favorable microbenchmarks + // Note--initialization catches step == 0 so we don't need to here + if (!isEmpty) { + var i = start + while (true) { + f(i) + if (i == lastElement) return + i += step + } } } @@ -285,7 +281,7 @@ extends scala.collection.AbstractSeq[Int] */ final override def splitAt(n: Int) = (take(n), drop(n)) - /** Creates a new range consisting of the `length - n` last elements of the range. + /** Creates a new range consisting of the last `n` elements of the range. * * $doesNotUseBuilders */ @@ -347,18 +343,19 @@ extends scala.collection.AbstractSeq[Int] // this is normal integer range with usual addition. arithmetic series formula can be used if (isEmpty) 0 else if (numRangeElements == 1) head - else (numRangeElements.toLong * (head + last) / 2).toInt + else ((numRangeElements * (head.toLong + last)) / 2).toInt } else { // user provided custom Numeric, we cannot rely on arithmetic series formula if (isEmpty) num.toInt(num.zero) else { var acc = num.zero var i = head - while(i != terminalElement) { + while (true) { acc = num.plus(acc, i) + if (i == lastElement) return num.toInt(acc) i = i + step } - num.toInt(acc) + 0 // Never hit this--just to satisfy compiler since it doesn't know while(true) has type Nothing } } } |