May be.
import java.util
object RowPerformanceTest {
val dsSize = 100000
val rowSize = 20
val repeatCnt = 1000
var startTime:Long = _
var endTime: Long = _
val columnMap: util.HashMap[String,Int] = {
val result = new util.HashMap[String,Int]
var j = 0
while(j<rowSize){
result.put(s"column_$j",j)
j=j+1
}
result
}
val dummyArray:Array[Int] = {
val result = new Array[Int] (rowSize)
columnMap.forEach{ (n,i) =>
result(i)=i
}
result
}
val columnArray:Array[String] = {
val result = new Array[String] (rowSize)
columnMap.forEach{ (n,i) =>
result(i)=n
}
result
}
val dataSet:Array[Array[Long]] = {
val result = new Array[Array[Long]](dsSize)
var i = 0
while(i<dsSize){
val array = new Array[Long](rowSize)
result(i) = array
var j = 0
while(j<columnArray.length){
array(j)=1
j=j+1
}
i=i+1
}
result
}
def begin(): Unit ={
startTime = System.nanoTime()
}
def end(): Unit = {
endTime = System.nanoTime()
}
def main(args: Array[String]): Unit = {
def testByKey(): Unit ={
var i = 0
var sum = 0L
while(i<dataSet.length){
var j = 0
val row = dataSet(i)
while(j<columnArray.length){
sum = sum + row(columnMap.get(columnArray(j)))
j=j+1
}
i=i+1
}
//println(s"testByKeySum:$sum")
}
def testByIndex(): Unit = {
var i = 0
var sum = 0L
while(i<dataSet.length){
val row = dataSet(i)
var j = 0
while(j<row.length){
sum = sum + row(dummyArray(j))
j=j+1
}
i=i+1
}
//println(s"testByIndex:$sum")
}
begin()
testByKey()
end()
begin()
for(i<-1 to repeatCnt){
testByKey()
}
end()
println("by key")
val byKeyTotolTime = BigDecimal(endTime-startTime)/1000000000
println(s" total time:$byKeyTotolTime")
begin()
testByIndex()
end()
begin()
for(i<-1 to repeatCnt) {
testByIndex()
}
end()
println("by index")
val byIndexTotolTime = BigDecimal(endTime-startTime)/1000000000
println(s" total time:$byIndexTotolTime")
println("ratio")
println(s" time:${byKeyTotolTime/byIndexTotolTime}")
}
}
Output
by key
total time:12.119882852
by index
total time:1.641546377
ratio
time:7.383210746777457631341718711612130
It is 7 times slower.
May be I have mistaken somewhere.
May be it is very unusual case.