I was wondering which is more efficient and why?
1)
List<Blah> foo;
...
return ImmutableList.copyOf(foo);
or
2)
List<Blah> foo;
...
return new ImmutableList.Builder<Blah>().addAll(foo).build();
Immutable List Static Factory Methods. The List. of static factory methods provide a convenient way to create immutable lists. A list is an ordered collection, where duplicate elements are typically allowed.
In Java 8 and earlier versions, we can use collection class utility methods like unmodifiableXXX to create immutable collection objects. If we need to create an immutable list then use the Collections. unmodifiableList() method.
I don't see any reason why you should use builder here:
ImmutableList.copyOf
is much more readable than making a Builder
in this case, Builder
doesn't infer generic type and you have to specify type by
yourself when used as one-liner,ImmutableList.copyOf
does good magic when invoked with another immutable collection (attempts to avoid actually copying the data when it is safe to do so),Builder#addAll
invokes addAll
on previously created ArrayList
while copyOf
avoids creating any list for zero- and one-element collections (returns empty immutable list and singleton immutable list respectively),copyOf(Collection)
instance doesn't create temporary ArrayList
(copyOf(Iterable)
and copyOf(Iterator)
does so),Builder#build
invokes copyOf
on previously internally populated ArrayList
, what brings you to your question - why use Builder
here, when you have copyOf
?P.S. Personally I use ImmutableList.builder()
static factory instead of new ImmutableList.Builder<Blah>()
constructor - when assigned to a Builder<Blah>
variable the first infers generic type while the latter doesn't.
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