The test is badly written. You can't learn much of anything from it.
It is true that accessors like get
take some time, but e.g. the Sun JVM can optimize many of those away to almost nothing. In particular, ArrayList
get needn't really take any significant extra time.
Here's a benchmark (written in Scala, but using Java's arrays and ArrayList
) demonstrating just how small the difference is when you're actually using (all of) the values in your array:
object ArraySpeed {
def ptime[A](f: => A) = {
val t0 = System.nanoTime
val ans = f
printf("Elapsed: %.3f seconds\n",(System.nanoTime-t0)*1e-9)
ans
}
val a = Array.range(0,1000000).map(x => new java.lang.Integer(x))
val b = new java.util.ArrayList[java.lang.Integer]
a.foreach(x => b.add(x))
var j = 0
def jfroma = {
var i=0
while (i<1000000) {
j += a(i).intValue
i += 1
}
j
}
def jfromb = {
var i=0
while (i<1000000) {
j += b.get(i).intValue
i += 1
}
j
}
def main(args: Array[String]) {
for (i <- 1 to 5) {
ptime(for (j <- 1 to 100) yield jfroma)
ptime(for (j <- 1 to 100) yield jfromb)
println
}
}
}
Running it gives:
$ scalac ArraySpeed.scala
$ scala ArraySpeed
Elapsed: 0.324 seconds // This is direct array access
Elapsed: 0.378 seconds // This is ArrayList
Elapsed: 0.326 seconds
Elapsed: 0.389 seconds
Elapsed: 0.355 seconds
Elapsed: 0.349 seconds
Elapsed: 0.323 seconds
Elapsed: 0.333 seconds
Elapsed: 0.318 seconds
Elapsed: 0.331 seconds
And Scala bytecode for stuff like this is pretty much identical to the Java bytecode, so this is a pretty fair comparison. (The scala
command is just a wrapper to call java
with the right library in the classpath.)