Java 9, Set.of() and Map.of() varargs overloads

Schidu Luca :

I'm studying the factory methods for Immutable collections. I see the Set.of() method has 10 varargs overloading (same for Map.of()). I really can't understand why there are so many. In the end the function ImmutableCollections.SetN<>(elements) gets called anyway.

In the documentation I found this:

While this introduces some clutter in the API, it avoids array allocation, initialization, and garbage collection overhead that is incurred by varargs calls.

Is the clutter indeed worth the performance gain? If yes, would that ideally do create a separate method for any N elements?

Eugene :

At the moment that method is called anyway - this could change. For example it could be that it creates a Set with only three elements, 4 and so on.

Also not all of them delegate to SetN - the ones that have zero, one and two elements have actual classes of ImmutableCollections.Set0, ImmutableCollections.Set1 and ImmutableCollections.Set2

Or you can read the actual question regarding this ... here Read the comments from Stuart Marks in that question -as he is the person that created these Collections.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=428025&siteId=1