scala性能测试

主要对比scala 的for, while循环,以及和java for while循环作对比

scala代码

object TestScalaClass {
  var maxindex = 100000

  def testloopfor(): Unit ={
    var beg = System.currentTimeMillis()
    var sum = 0
    for (i <- 0 to  maxindex) {
      sum += i
    }

    println("value " + sum +  " 耗时: " + (System.currentTimeMillis() - beg))
  }

  def testswhile(): Unit ={
    var beg = System.currentTimeMillis()
    var sum = 0
    var i = 0;
    while (i < maxindex ){
      i+=1
      sum += i
    }
    println("value " + sum +  " 耗时: " + (System.currentTimeMillis() - beg))
  }


   def main (args: Array[String]) {
     testswhile()
     testloopfor()

  运行结果 

time1

value 705082704 耗时: 338
value 705082704 耗时: 13 

time2

value 705082704 耗时: 271
value 705082704 耗时: 11

time3

value 705082704 耗时: 289
value 705082704 耗时: 10

可以看出在scala 中 for循环比while循环慢接近30倍

java测试代码

	  long begtime = System.currentTimeMillis();
	  int i = 0;
	  int sum = 0;
	  for (i = 0 ; i < 100000; i++)
		  sum += i;
		  
	  long endtime = System.currentTimeMillis();
	  System.out.println("耗时: " + (endtime - begtime) );
	  
//	  long begtime = System.currentTimeMillis();
//	  int i = 0;
//	  int sum = 0;
//	  
//	  while(i <100000){
//		  i++;
//		  sum += i;
//	  }
//		  
//	  long endtime = System.currentTimeMillis();
//	  System.out.println("耗时: " + (endtime - begtime) );

  在java中,for循环和while循环两者效率相差不大,运行时间集中在1-10之间,平均3ms左右 ,比scala的while循环也快几倍。

scala 测试hashmap

   def testhashmap(): Unit ={
     print("
 scala hashmap 
")
     var buf = new scala.collection.mutable.HashMap[String, String]()
     var beg = System.currentTimeMillis()
     var i = 0
     while (i <= 100000){
       buf += (i.toString -> i.toString)
       i +=1
     }
//     for (i <- 0 to 100000){
//       buf += (i.toString -> i.toString)
//     }
     buf += ("11" -> "11")
     println(System.currentTimeMillis() - beg)
     beg = System.currentTimeMillis()
     //buf.foreach(f=>print("key: " + f._1 + "value :" + f._2 + "	"))

     print("
 java hashmap 
")
     var javamap  = new JavaHashMap[String, String]()

     i = 0
     while (i <= 100000){
       javamap.put(i.toString, i.toString)
       i +=1
     }
//
//     for(i <- 0 to 100000){
//       javamap.put(i.toString, i.toString)
//     }

//     for(i <- javamap.keySet().toArray()){
//       print("key:= " + i  + " value " + javamap.get(i) + "	")
//     }
     println(System.currentTimeMillis() - beg)
   }

使用while循环

scala hashmap
216

java hashmap
64

使用for循环

scala hashmap
299

java hashmap
89

while效率相对高点。

原文地址:https://www.cnblogs.com/chengxin1982/p/4034186.html