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?
CodePudding user response:
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>[]
.)
CodePudding user response:
I believe the second, with List.empty actually clears the current list, without creating a reference to a new one, regardless if = []
or = const []
. Interesting question though.