Skip to content

Instantly share code, notes, and snippets.

@ryan-williams
Created August 25, 2015 15:14
Show Gist options
  • Save ryan-williams/d8a6e6afa716ff08f187 to your computer and use it in GitHub Desktop.
Save ryan-williams/d8a6e6afa716ff08f187 to your computer and use it in GitHub Desktop.
Scala element appending to Lists, Arrays, Vectors
scala> def time(n: Int) = { def t = System.currentTimeMillis; val before = t; (1 to n).foldLeft[List[Int]](Nil)((l,i) => l :+ i); val after = t; after - before }
time: (n: Int)Long
scala> time(10000)
res10: Long = 1604
scala> time(10000)
res11: Long = 1585
scala> time(20000)
res12: Long = 6249
scala> time(20000)
res13: Long = 6233
scala> time(40000)
res14: Long = 28922
scala> def timeArr(n: Int) = { def t = System.currentTimeMillis; val before = t; (1 to n).foldLeft[Array[Int]](Array[Int]())((l,i) => l :+ i); val after = t; after - before }
timeArr: (n: Int)Long
scala> timeArr(10000)
res15: Long = 75
scala> timeArr(10000)
res16: Long = 42
scala> timeArr(20000)
res17: Long = 151
scala> timeArr(20000)
res18: Long = 161
scala> timeArr(40000)
res19: Long = 586
scala> timeArr(40000)
res20: Long = 604
scala> timeArr(80000)
res21: Long = 2528
scala> timeArr(80000)
res22: Long = 2564
scala> def timeVec(n: Int) = { def t = System.currentTimeMillis; val before = t; (1 to n).foldLeft[Vector[Int]](Vector[Int]())((l,i) => l :+ i); val after = t; after - before }
timeVec: (n: Int)Long
scala> timeVec(10000)
res23: Long = 32
scala> timeVec(10000)
res24: Long = 5
scala> timeVec(10000)
res25: Long = 357
scala> timeVec(10000)
res26: Long = 1
scala> timeVec(10000)
res27: Long = 1
scala> timeVec(10000)
res28: Long = 2
scala> timeVec(10000)
res29: Long = 1
scala> timeVec(20000)
res30: Long = 2
scala> timeVec(20000)
res31: Long = 2
scala> timeVec(40000)
res32: Long = 4
scala> timeVec(40000)
res33: Long = 6
scala> timeVec(80000)
res34: Long = 8
scala> timeVec(80000)
res35: Long = 7
scala> timeVec(160000)
res36: Long = 13
scala> timeVec(160000)
res37: Long = 9
scala> timeVec(320000)
res38: Long = 25
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment