Performance of variable argument methods in Java

前端 未结 6 1184
小鲜肉
小鲜肉 2020-12-19 20:42

I have this question about the performance of a method in Java with a variable number of parameters.

Say I have the following 2 alternatives:

public          


        
6条回答
  •  庸人自扰
    2020-12-19 20:52

    to @Canonical Chris

    I don't think problem at your test come from variable argument. The function sumationVArgs take more time to complete because of for loop.

    I created this function and added to the benchmark

    int summationVArgs2(int... args) {
            return args[0] + args[1] + args[2] + args[3] + args[4] + args[5];
        }
    

    and this is what I see:

    028:1000000 Fixed-Args: 0 ms
    028:1000000 Vargs-Args: 12 ms
    028:1000000 Vargs2-Args2: 0 ms
    

    The for loop in function "summationVArgs" is compiled to more operations than add function. It contains add operation to increase iterator, check operation to check condition and branch operation to loop and exit loop, and all of them execute once for each loop except branch opration to exit loop.

    Sorry for my bad English. I hop you can understand my English :)

提交回复
热议问题