Initializing a list with a chain of add
or addAll
invocations is less efficient than making the initialization with a
single list literal. Each invocation has a cost in itself, and each list argument of the addAll
method is instantiated to only be
temporarily used for the insertion.
Invoking a method that includes lists constructed using such a pattern may lead to performance issues, on CPU usage as well as on memory
allocations.
On top of the performance argument, the list literal is more concise and easier to read.
Exceptions
The rule does not apply to other collection literals that expose the add
or addAll
methods, such as
Set
s.
final aSet = <int>{}..add(3)..add(4); // Not applicable
The rule does not apply when the chain of invocations doesn’t start with a List
literal:
final aList = ...;
aList..add(43)..add(44); // Not applicable
l1..addAll([43, 44])..add(45); // Not applicable