Varargs performance of Java

Let me check the vararg performance of Java

I write the following test code:

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,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) {
    }
}

On my machine, the average output is:

78
4696
78

It seems that passing variables to methods is free! well!

But using varags is 60 times slower! Why?

One explanation may be that the program must create arrays on the heap, and the time is spent by GC But for fewer loops, I can still get the output:

0
62
0

What is taking this extra time anyway, the compiler has all the information to solve this modified variable call

This is not what I intend to optimize, but I find this curious

to update

I added a new test

t = System.currentTimeMillis();
for (int i = 0; i < n; i++) {
    baz(s1);
}
System.err.println(System.currentTimeMillis() - t);

The parameter version is 30 times slower Maybe there is an ArrayList behind the scene toArray()?

So, notice the unwanted varags methods in your code and refactor to fix the length This may be a performance improvement

Solution

The static list of parameters is completely different from an array When you pass in this way, the compiler reserves space for references and populates them when the method is called

Varargs is the equivalent of an array To call this method, it is necessary to create and populate an array at run time That's why you observe differences

String [] and string... Are synonymous If you compare them, you should see the same performance

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>