编码我到处检查Java的可变参数性能。Java的可变参数性能
我写下面的测试代码:
public class T {
public static void main(String[] args) {
int n = 100000000;
String s1 = new String("");
String s2 = new String("");
String s3 = new String("");
String s4 = new String("");
String s5 = new String("");
long t = System.currentTimeMillis();
for (int i = 0; i < n; i++) {
foo();
}
System.err.println(System.currentTimeMillis() - t);
t = System.currentTimeMillis();
for (int i = 0; i < n; i++) {
baz(s1, s2, s3, s4, s5);
}
System.err.println(System.currentTimeMillis() - t);
t = System.currentTimeMillis();
for (int i = 0; i < n; i++) {
bar(s1, s2, s3, s4, s5);
}
System.err.println(System.currentTimeMillis() - t);
}
static void foo() {
}
static void bar(String a1, String a2, String a3, String a4, String a5) {
}
static void baz(String... a) {
}
}
在我的机器的平均产量是:
78
4696
78
似乎传递变量的方法是不花钱?!很好!
但是使用varags的速度要慢60倍!为什么?
解释可能是程序必须在堆上创建数组,并且时间是由GC支出的。但是对于少环路我仍然得到作为输出:
0
62
0
什么是花这个额外的时间,反正编译器的所有信息来解决这一个修复可变调用...
它不是我的本意以优化,但我发现这个奇怪...
更新
我添加了一个新的测试
t = System.currentTimeMillis();
for (int i = 0; i < n; i++) {
baz(s1);
}
System.err.println(System.currentTimeMillis() - t);
而这一个参数版本仍然慢30倍。也许在场景后面有一个ArrayList.toArray()?
因此,请注意代码中的不需要的varags方法和重构来修复长度。这可能是性能提升。
是的,它将是相同的,因为可变参数是在有效编译之前将语法糖转换为数组调用。 – Riduidel 2010-03-11 16:00:59
这基本上是正确的,虽然我认为你应该澄清,差异是可变参数需要JVM分配和填充数组。不管它堆在堆栈上还是堆栈都不是问题(虽然当然是堆在堆上)。 – 2010-03-12 09:47:53
@肖恩欧文谢谢,更新。 – 2010-03-12 09:59:21