markovuksanovic markovuksanovic - 1 year ago 106
Dart Question

Dartlang const constructor - how is it different to "regular" constructor

I've noticed it's posible to create a const constructor in Dart. In docs it says that const word is used to denote something a compile time constant. I was wondering how what happens when I use a const constructor to create an object? Is this like a an immutable object which is always the same and available at compile time? How does the concept of "const constructor" actually work?

Answer Source

Const constructor creates a "canonicalized" instance.

That is, all constant expressions begin canonicalized, and later these "canonicalized" symbols are used to recognize equivalence of these constants.


A process for converting data that has more than one possible representation into a "standard" canonical representation. This can be done to compare different representations for equivalence, to count the number of distinct data structures, to improve the efficiency of various algorithms by eliminating repeated calculations, or to make it possible to impose a meaningful sorting order.

This means that const expressions like const Foo(1, 1) can represent any usable form that is useful for comparison in virtual machine.

The VM only needs to take into account the value type and arguments in the order in which they occur in this const expression. And, of course, they are reduced for optimization.

Constants with the same canonicalized values:

var foo1 = const Foo(1, 1); // #Foo#int#1#int#1
var foo2 = const Foo(1, 1); // #Foo#int#1#int#1

Constants with different canonicalized values (because signatures differ):

var foo3 = const Foo(1, 2); // $Foo$int$1$int$2
var foo4 = const Foo(1, 3); // $Foo$int$1$int$3

var baz1 = const Baz(const Foo(1, 1), "hello"); // $Baz$Foo$int$1$int$1$String$hello
var baz2 = const Baz(const Foo(1, 1), "hello"); // $Baz$Foo$int$1$int$1$String$hello

Constants are not recreated each time. They are canonicalized at compile time and stored in special lookup tables (where they are hashed by their canonical signatures) from which they are later reused.


The form #Foo#int#1#int#1 used in these samples is only used for comparison purposes and it is not a real form of canonicalization (representation) in Dart VM;

But the real canonicalization form must be "standard" canonical representation.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download