I have been wondering if dynamic types are slower in Dart.
Example given:
final dynamic example = "Example"
versus
final String example = "Example"
Yes, using dynamic
typed variables in Dart is often slower than using variables typed with an actual type.
However, your example is not using dynamic
as type, it is using type inference to infer the String
type. That might cost a little extra at compile-time, but at run-time, your two code examples are completely identical. Both variables are typed as String
.
A dynamic
method invocation may be slower because the run-time system must add extra checks to ensure that the variable can do the things you are trying to do with it.
If you have int x = 2; print(x + 3);
the run-time system knows that int
has a +
operator, and even knows what it is.
If you write dynamic x = 2; print(x + 3);
, the run-time system must first check whether x
has a +
operator before it can call it, and find that operator's definition on the object before calling it. It might not always be slower, some cases optimize better than others, but it can never be faster.
Not all code is performance sensitive, and not all variables can be typed. If you have a variable that holds either a String
or a List
, and you want to know the length, just writing stringOrList.length
is more convenient than stringOrList is String ? stringOrList.length : (stringOrList as List).length
. It may be slower depending on the compiler and the target platform.
Well, in your first example (heh), example
is inferred to be a type String
, not dynamic
, so how could it be slower? The style guide even recommends not adding redundant types to those variables that can be inferred correctly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With