Search code examples
javaguava

Guava ImmutableList copyOf vs Builder


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();

Solution

  • 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,
    • (from docs) 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),
    • (from source) 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),
    • (from source) copyOf(Collection) instance doesn't create temporary ArrayList (copyOf(Iterable) and copyOf(Iterator) does so),
    • (from source) moreover, 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.