I recently found out that you can initialize Lists in Java by calling the Collections.nCopies()
method rather than using a for-loop. But that got me wondering, is there a performance advantage/disadvantage in using this method over a for-loop or is it just a simpler way of doing the same thing?
Since the collection returned by nCopies
is immutable, the entries in this collection need not be "materialized". In other words, all that is needed is a space for a single object of type T
; everything else is an implementation of the collection interface that pretends to have a collection of N
objects, but in reality has only one object that it returns N
times.
This may prove to give you a lot of improvement in space when the collection you are creating is large: in fact, the larger the collection, the bigger is your savings compared to a real collection that you initialize with a for
loop.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With