user973479
user973479

Reputation: 1659

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

Upvotes: 16

Views: 9364

Answers (2)

Maverick Meerkat
Maverick Meerkat

Reputation: 6404

Builder allows you to add stuff. I.e. if you need to add another object it might be easier to do with the Builder pattern:

ImmutableList<SomeModel> newModelObjects = new ImmutableList.Builder<SomeModel>()
    .addAll(getModelObjects()).add(newModelObject).build();

As opposed to:

ArrayList<SomeModel> list = new ArrayList<>(getModelObjects());
list.add(newModelObject);
ImmutableList<SomeModel> newModelObjects = ImmutableList.copyOf(list);

Upvotes: 0

Grzegorz Rożniecki
Grzegorz Rożniecki

Reputation: 28005

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.

Upvotes: 32

Related Questions