What's the most efficient way to make a single-item Iterable in Dart?

472 Views Asked by At

In Dart, single-item iterables can be created in various ways.

['item']; // A single-item list

Iterable.generate(1, (_) => 'item'); // A single-item generated Iterable

How do these methods compare in terms of speed and memory usage, during both creation and iteration?

1

There are 1 best solutions below

0
On BEST ANSWER

The list is probably the cheapest.

At least if you use a List.filled(1, 'item') to make it a fixed-length list, those are cheaper than growable lists.

You need to store the one element somehow. Storing it directly in the list takes a single reference. Then the list might spend one more cell on the length (of 1).

On top of that, compilers know platform lists and can be extra efficient if they can recognize that that's what they're dealing with. They probably can't here, since you need an iterable to pass to something expecting an arbitrary iterable, because otherwise a single element iterable isn't useful.

It's a little worrying that the list is mutable. If you know the element at compile time, a const ['item'] is even better.

Otherwise Iterable.generate(1, constantFunction) is not a bad choice, if you know the value at compile time and can write a String constantFunction() => 'item'; static or top-level function that you can tear off efficiently.

That said, none of the things here really matter for performance, unless you're going to do it a lot of times in a single run of your program. The difference in timing is going to be minimal. The difference in memory usage is likely less than the size of the Iterator being created by either method.

You'll save much more by not using a for (var e in iterable) on an iterable, and, say, use for (var i = 0; i < list.length; i++) { var e = list[i]; ... } instead, if you can ensure that the iterable is always a list.