Created
March 12, 2014 05:42
-
-
Save chidakiyo/9501494 to your computer and use it in GitHub Desktop.
Scalaでリストに要素を追加する処理をmutable/immutableで比較してみた
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package util | |
import java.util.Date | |
import scala.collection.mutable.ListBuffer | |
import scala.collection.mutable.MutableList | |
object Benchmark { | |
val END = 10000000 | |
def main(args: Array[String]) { | |
benchmark("a")(aTest) | |
benchmark("b")(bTest) | |
benchmark("c")(cTest) | |
println("---") | |
benchmark("a")(aTest) | |
benchmark("b")(bTest) | |
benchmark("c")(cTest) | |
println("---") | |
benchmark("a")(aTest) | |
benchmark("b")(bTest) | |
benchmark("c")(cTest) | |
println("---") | |
benchmark("a")(aTest) | |
benchmark("b")(bTest) | |
benchmark("c")(cTest) | |
println("---") | |
benchmark("a")(aTest) | |
benchmark("b")(bTest) | |
benchmark("c")(cTest) | |
println("---") | |
} | |
def benchmark[R](s: String)(f: => R): R = { | |
val start = new Date().getTime | |
val r = f | |
val end = new Date().getTime | |
println(s + " " + (end - start) + " msec.") | |
r | |
} | |
def aTest(): List[Int] = { | |
var result: List[Int] = Nil | |
for (i <- (0 to END)) { | |
result = i :: result | |
} | |
result | |
} | |
def bTest(): ListBuffer[Int] = { | |
val result: ListBuffer[Int] = new ListBuffer | |
for (i <- (0 to END)) { | |
result += i | |
} | |
result | |
} | |
def cTest(): MutableList[Int] = { | |
val result: MutableList[Int] = new MutableList | |
for (i <- (0 to END)) { | |
result += i | |
} | |
result | |
} | |
} | |
// -- RESULTS -- // | |
// a 8715 msec. | |
// b 4987 msec. | |
// c 3734 msec. | |
// --- | |
// a 3365 msec. | |
// b 3740 msec. | |
// c 5886 msec. | |
// --- | |
// a 1170 msec. | |
// b 5762 msec. | |
// c 3289 msec. | |
// --- | |
// a 4963 msec. | |
// b 2392 msec. | |
// c 5808 msec. | |
// --- | |
// a 1328 msec. | |
// b 5837 msec. | |
// c 3520 msec. | |
// --- |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment