I collect all possible method and benchmark it using benchmark_harness package.
According to the result the recommended method is:
final List<int> c = a + b;
final List<int> c = [...a, ...b];
Here is the benchmark code:
import 'package:benchmark_harness/benchmark_harness.dart';
List<int> a = [1, 2, 3];
List<int> b = [4, 5, 6];
class Benchmark1 extends BenchmarkBase {
const Benchmark1() : super('c = a + b ');
@override
void run() {
final List<int> c = a + b;
}
}
class Benchmark2 extends BenchmarkBase {
const Benchmark2() : super('c = a.followedBy(b).toList() ');
@override
void run() {
final List<int> c = a.followedBy(b).toList();
}
}
class Benchmark3 extends BenchmarkBase {
const Benchmark3() : super('c = [a, b].expand((x) => x).toList() ');
@override
void run() {
final List<int> c = [a, b].expand((x) => x).toList();
}
}
class Benchmark4 extends BenchmarkBase {
const Benchmark4() : super('c = [a, b].reduce((value, element) => value + element) ');
@override
void run() {
final List<int> c = [a, b].reduce((value, element) => value + element);
}
}
class Benchmark5 extends BenchmarkBase {
const Benchmark5() : super('c = [a, b].fold([], (previousValue, element) => previousValue + element) ');
@override
void run() {
final List<int> c = [a, b].fold([], (previousValue, element) => previousValue + element);
}
}
class Benchmark6 extends BenchmarkBase {
const Benchmark6() : super('a.addAll(b) ');
@override
void run() {
a.addAll(b);
}
}
class Benchmark7 extends BenchmarkBase {
const Benchmark7() : super('c = <int>[...a, ...b] ');
@override
void run() {
final List<int> c = <int>[...a, ...b];
}
}
class Benchmark8 extends BenchmarkBase {
const Benchmark8() : super('c = List.from(a)..addAll(b) ');
@override
void run() {
final List<int> c = List.from(a)..addAll(b);
}
}
void main() {
// Benchmark1().report();
// Benchmark2().report();
// Benchmark3().report();
// Benchmark4().report();
// Benchmark5().report();
// Benchmark6().report();
// Benchmark7().report();
Benchmark8().report();
}
And the result:
c = a + b (RunTime): 0.8384643860155879 us.
c = a.followedBy(b).toList() (RunTime): 1.3018350015264015 us.
c = [a, b].expand((x) => x).toList() (RunTime): 2.194391139053011 us.
c = [a, b].reduce((value, element) => value + element) (RunTime): 1.1215188056273329 us.
c = [a, b].fold([], (previousValue, element) => previousValue + element) (RunTime): 1.7163271628511283 us.
a.addAll(b) (RunTime): 1.08603684815237 us.
c = <int>[...a, ...b] (RunTime): 0.8498483658053312 us.
c = List.from(a)..addAll(b) (RunTime): 0.9107294347150762 us.
[list1, list2, list3, ...].expand((x) => x).toList()
; – Imaginative