Is 'List.empty(growable: false)' or 'const []' more efficient in Dart?
const <T>[]
creates a canonical, compile-time constant. The List<T>
object is constructed only once.
In contrast, List<T>.empty(growable: false)
has no such guarantee and can create new List<T>
objects. (Arguably it could return a const List<T>
object when growable
is false
, but then that would require a runtime check on growable
, so that too would be slightly less efficient. As you've already noted, it can't do any better than const <T>[]
.)
harlekintiger
Updated on January 01, 2023Comments
-
harlekintiger over 1 year
Hello fellow Coders,
I was wondering whetherconst []
is more efficient thanList.empty(growable: false)
. The latter sound more like the official way to go about it, but because I can't make it const it has to allocates a new array. Whereas the first is not only shorter but because it is const I don't see how it isn't more efficient.
Does anyone has more insight/ knows how to check the actual performance? -
harlekintiger over 2 yearsWait, just so that we're on the same page: I'm not talking about
instanceOfList.empty()
, im talking about the static method from the List class - literallyList.empty
. One of the few legal constructors of list.