Variable vs Fixed Parameters Method Call

In this article I would like to reveal the differences and what happens under the hood between a variable parameters method and the same version but with fixed number of parameters, from a performance standpoint.

In regards to that I wrote a small program which tests the response time of calling a method with 2, 4, 6, 8, 10 fixed parameters versus the analogous varargs version. Please find the code below:

As we might easily notice, the explicit params version is faster and stick around 2 or 3 ns/op as opposite to varargs version which is always slower. Now, let’s see why exactly, what is the difference between these two.

As spotted by assembly code above, before calling the variable parameters method:

a new array is allocated

all stack parameters (i.e. the varargs) are collected and assigned to the new array

then the effective method is called by passing the newly allocated array as input

To summarize, a variable parameters method has an extra cost associated to a new array allocation and additional stack parameter manipulation which does not happen in case of calling a method with fixed number of parameters, which might explain the difference in response time between these two versions.

As a performance optimization advice, you can rely on this trick by declaring methods with explicit parameters for intensively or widely used APIs. A very good example is the Collection Factory Methods added in JDK 9 (e.g. see List.of() or Set.of() or Map.of() ) which have dedicated implementations for a number of less or equal than 10 parameters and starting with the 11-th parameter there is a varargs method.