Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are dynamic types slower in Dart?

I have been wondering if dynamic types are slower in Dart.

Example given:

final dynamic example = "Example"

versus

final String example = "Example"
like image 559
TheUniqueProgrammer Avatar asked Sep 13 '18 23:09

TheUniqueProgrammer


2 Answers

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.

like image 132
lrn Avatar answered Nov 15 '22 01:11

lrn


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.

like image 2
Randal Schwartz Avatar answered Nov 15 '22 00:11

Randal Schwartz