由于集合遵循的是 Iterable
协议,这个协议并不需要集合随时知道它的长度。因此调用.length
的时候,其实相当于是遍历了一遍,执行速度是很低的。这是获取 length
的实现方法:
int get length {
assert(this is! EfficientLengthIterable);
int count = 0;
Iterator it = iterator;
while (it.moveNext()) {
count++;
}
return count;
}
因此,更高效地判断集合是否为空的做法是使用.isEmpty
或 .isNotEmpty
。
bool get isEmpty => !iterator.moveNext();