在许多网站中我研究过scala比Java快。我编写了代码来测试这两者之间的时差,但Scala需要更多时间。我不知道自己是否犯了任何错误。如果我错了,请纠正我。
Scala代码
package com.first
import java.util.ArrayList
object Word extends App{
val absoluteResult = new ArrayList[Any]()
val before = System.currentTimeMillis()
var i =0
while (i<10000) {
i = i+1
val result = List("foo", 23, true).iterator
while (result.hasNext) {
absoluteResult.add(foo(result.next))
}
}
println("Took : "+(System.currentTimeMillis() - before)
+" ms, number of elements : "+absoluteResult.size)
def foo(obj : Any) =
obj match {
case _:String => "String"
case _:Boolean => "Boolean"
case _:Integer => "Integer"
case _ => throw new IllegalArgumentException()
}
}
输出 采取:142毫秒,元素数量:30000
Java代码
package com.first;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class quicksort {
public static void main(String[] args) {
List<Object> absoluteResult = new ArrayList<Object>();
long before = System.currentTimeMillis();
for (int i=0; i < 10000; i++) {
List<Object> result = new ArrayList<Object>();
result.add("foo");
result.add( 23);
result.add(true);
for (Object y : result) {
absoluteResult.add(foo(y));
}
}
System.out.println("Took : "+(System.currentTimeMillis() - before)
+" ms, number of elements : "+absoluteResult.size());
}
static String foo(Object s) {
if (s instanceof String) {
return "String";
} else if (s instanceof Boolean) {
return "Boolean";
} else if (s instanceof Integer) {
return "Integer";
} else {
throw new IllegalArgumentException();
}
}
}
输出 采取:30毫秒,元素数量:30000