Skip to content

Commit add83b8

Browse files
author
Dima Tkach
committed
Override .slice in ArrayOps to use arraycopy.
This makes it ~10x faster when copying large chunks arround. My benchmark: def bm(duration: Long)(f: => Unit): Int = { val end = System.currentTimeMillis + duration var count = 0 while(System.currentTimeMillis < end) { f count += 1 } count } def measure(seconds: Int)(f: => Unit) = (1 to seconds).map { _ => bm(1000)(f) }.sum / seconds val array = scala.util.Random.alphanumeric.take(1000).toArray measure(20) { array.slice(100, 500) } // ~5 million measure(20) { scala.collection.WrappedArray(array).slice(100, 500) } // ~300K
1 parent 4e95083 commit add83b8

File tree

1 file changed

+11
-0
lines changed

1 file changed

+11
-0
lines changed

src/library/scala/collection/mutable/ArrayOps.scala

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,17 @@ sealed trait ArrayOps[T] extends Any with ArrayLike[T, Array[T]] with CustomPara
4141
if (l > 0) Array.copy(repr, 0, xs, start, l)
4242
}
4343

44+
override def slice(from: Int, until: Int): Array[T] = {
45+
val lo = math.max(from, 0)
46+
val hi = math.min(math.max(until, 0), repr.length)
47+
val size = math.max(hi-lo, 0)
48+
val result = java.lang.reflect.Array.newInstance(elementClass, size)
49+
if(size > 0) {
50+
Array.copy(repr, lo, result, 0, size)
51+
}
52+
result.asInstanceOf[Array[T]]
53+
}
54+
4455
override def toArray[U >: T : ClassTag]: Array[U] = {
4556
val thatElementClass = implicitly[ClassTag[U]].runtimeClass
4657
if (elementClass eq thatElementClass)

0 commit comments

Comments
 (0)