Is 'List.empty(growable: false)' or 'const []' more efficient in Dart?

644

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>[].)

Share:
644
harlekintiger
Author by

harlekintiger

Updated on January 01, 2023

Comments

  • harlekintiger
    harlekintiger over 1 year

    Hello fellow Coders,
    I was wondering whether const [] is more efficient than List.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
    harlekintiger over 2 years
    Wait, 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 - literally List.empty. One of the few legal constructors of list.