Skip to content

Instantly share code, notes, and snippets.

@ryanlecompte
Last active August 25, 2021 13:40
Show Gist options
  • Save ryanlecompte/5210745 to your computer and use it in GitHub Desktop.
Save ryanlecompte/5210745 to your computer and use it in GitHub Desktop.
mutable.ArrayBuffer vs immutable.Vector
import scala.collection._
import com.twitter.util._
scala> val buffer = mutable.ArrayBuffer.empty[Int]
scala> println(Time.measure { (0 to 50000000).foreach { buffer += _ } }.inMillis)
17610
scala> var vector = immutable.Vector.empty[Int]
scala> println(Time.measure { (0 to 50000000).foreach { vector :+= _ } }.inMillis)
7865
// do it again, just in case
scala> val buffer = mutable.ArrayBuffer.empty[Int]
scala> println(Time.measure { (0 to 50000000).foreach { buffer += _ } }.inMillis)
24742
// let's try a java.util.ArrayList
val buffer2 = new java.util.ArrayList[Int]
scala> println(Time.measure { (0 to 50000000).foreach { buffer2.add(_) } }.inMillis)
7923
@tanjucat
Copy link

tanjucat commented Nov 2, 2015

Making things a little more interesting than just inserting values into the collections (note the N is reduced here to 50,000):

import scala.collection._
import com.twitter.util._

object HelloWorld extends App {
    val N = 50000
    val reps = 100

    var timeVector: Long = 0
    var timeArray: Long = 0
    var timeArrayBuffer: Long = 0
    var timeQueue: Long = 0

    for (i <- 0 until reps) {
        var myArray = Array.ofDim[Int](N+1)
        val elapsed_prev3 = Time.measure{(0 to N).foreach((i: Int) => {myArray(i) = i; myArray.take(100).map(x=> x*x).sum})}.inMillis
        timeArray += elapsed_prev3

        val buffer = mutable.ArrayBuffer.empty[Int]
        val elapsed_prev = Time.measure{(0 to N).foreach {(i: Int) => {buffer += i; buffer.take(100).map(x=> x*x).sum} }}.inMillis
        timeArrayBuffer += elapsed_prev

        var vector = Vector.empty[Int]
        val elapsed_prev2 = Time.measure{(0 to N).foreach {(i: Int) => {vector :+= i; vector.take(100).map(x=> x*x).sum} }}.inMillis
        timeVector += elapsed_prev2

        var queue = mutable.Queue[Int]()
        val elapsed_prev4 = Time.measure{(0 to N).foreach {(i: Int) => {queue.enqueue(i); queue.take(100).map(x=> x*x).sum}}}.inMillis
        timeQueue += elapsed_prev4
    }

    println("timeVector     : " + timeVector + "  avg = " + timeVector/reps)
    println("timeArrayBuffer: " + timeArrayBuffer + "  avg = " + timeArrayBuffer/reps)
    println("timeArray      : " + timeArray + "  avg = " + timeArray/reps)
    println("timeQueue      : " + timeQueue + "  avg = " + timeQueue/reps)

}

gives the following result:

timeVector     : 15717  avg = 157
timeArrayBuffer: 15316  avg = 153
timeArray      : 15345  avg = 153
timeQueue      : 55822  avg = 558

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment