最近看的for和while循环速度测试的相关帖子,有说for快的,又说while快的。于是自己测试了一下
具体结果直接看测试
def main(args: Array[String]): Unit = {
testWhile()
testWhile()
testFor()
}
def testFor(): Unit = {
var sum = 0
val start = System.currentTimeMillis()
for (i <- 0 to 10000000) {
sum += 1
}
println(s"for time: ${System.currentTimeMillis() - start}, sum: ${sum}")
}
def testWhile(): Unit = {
var sum = 0
val start = System.currentTimeMillis()
var i = 0
while (i <= 10000000) {
sum += 1
i += 1
}
println(s"while time: ${System.currentTimeMillis() - start}, sum: ${sum}")
}
结果: