Scala和Java的循环性能对比

来源:互联网 发布:淘宝上门安装怎么设置 编辑:程序博客网 时间:2024/04/30 06:47

对比Scala 的for, while循环,以及和Java的for, while循环作对比:

运行环境:

CPU: Intel(R) Core(TM) i5-4200M CPU @ 2.50GHz * 4

RAM: 8.00G

集成开发环境:IntelliJ IDEA 14.0.2

Scala SDK: scala-sdk-2.11.4

JDK: jdk1.7.0_45

对比表格(毫秒):






Scala代码:

object TestScalaPerformance {  //循环次数  var maxindex = 10000  def testFor(): Unit = {    var sum = 0    var beg = System.currentTimeMillis()    for (i <- 0 to  maxindex)      sum += i    var end = System.currentTimeMillis()     println("Scala的" + maxindex + "次for循环耗时: " + (end - beg))  }  def testWhile(): Unit = {    var sum = 0    var i = 0;    var beg = System.currentTimeMillis()    while (i < maxindex) {      i += 1      sum += i    }    var end = System.currentTimeMillis()    println("Scala的" + maxindex + "次while循环耗时: " + (end - beg))  }  def main(args: Array[String]) {    testWhile()    testFor()  }}


Java代码:

public class TestJavaPerformance {    //循环次数    private static long maxindex = 10000;    public static void main(String[] args) {        testWhile();        testFor();    }    public static void testWhile() {        int i = 0;        int sum = 0;        long begtime = System.currentTimeMillis();        while(i < maxindex){            i++;            sum += i;        }        long endtime = System.currentTimeMillis();        System.out.println("Java的" + maxindex + "次while循环耗时: " + (endtime - begtime) );    }    public static void testFor() {        int i = 0;        int sum = 0;        long begtime = System.currentTimeMillis();        for (i = 0 ; i < maxindex; i++)            sum += i;        long endtime = System.currentTimeMillis();        System.out.println("Java的" + maxindex + "次for循环耗时: " + (endtime - begtime) );    }}


0 0