Wow! I have just realized that varargs methods in Java cause an array to be allocated when they are called. Not sure why I would expect anything different, but should there perhaps be some kind of pooling for the arrays? At least for the initial 0 to 8 sizes? Is there any workaround in Java to use varargs without causing an array allocation for every call?
EDIT: Please understand that leaking memory to the GC is just an unwanted overhead/latency. It is NOT a bug like some comments implied. Just because Java has GC does not mean you can create tons of garbage at will.
See the example of
EnumSet. the vararg methodis overloaded with
to avoid the vararg array creation if args are 5 or less. (EnumSet probably goes too far here)
I don’t think this is really a GC concern. The array created is dereferenced very quickly, such die-young garbage should have almost no impact to GC.
However, instantiating an array is a relatively expensive operation; since EnumSet.add() is very fast, the overhead of array creation can be quite noticeable; they probably did some benchmark, and decided it’s worthwhile to optimized with overloading for up to 5 args.