How are `const` objects instantiated?

Hey hey 🙂

A few of us are trying to understand how const classes are instantiated and the impact that has on memory usage for an app.

  • Are all instances of all the const declarations in your app loaded into memory on App Startup?
  • Is const Text('Foo') is created at runtime, but after that every const Text('Foo') just returns the same cached instance?
  • Is Dart “pre-compiling” the const instances, then loading them into memory when they’re first accessed?
  • Once a const object is created, is it garbage collected as usual or kept in memory?

Are all of these questions wrong!? 😛

Any help understand how const objects are instantiated and how that affects memory usage would be much appreciated 🙂

Author: Fantashit

2 thoughts on “How are `const` objects instantiated?

  1. A few things are specified, though: If you use a <constObjectExpression> like const A(42) to obtain a constant instance of A, and its instance variables have values which are identical to the result o of evaluating some other constant object expression (which could be the same syntax or some other expression which may or may not be textually identical), then the result must be o.

    In other words, if we’re going to create “the same value” then it must be the same object (which is the essence of canonicalization).

    Similar rules apply to composite literals (lists, maps, sets) except that they are order-dependent (so it’s not enough to be the same set, it must also have the same iteration order for its elements).

    This implies that you will see some savings with respect to space (and, in practice, you won’t actually create the new object and check that it’s member-wise equal to an existing one, you’ll decide already at compile-time or link-time that you must use that other one, so you will save some time, too).

  2. In AOT environment (Flutter release builds) all constant objects are evaluated and canonicalized at compile time, then serialized into snapshot. When you start your application the snapshot is loaded into memory and all constants come into existence. They are not loaded lazily. They are never garbage collected.

    Hope this answers the question.

Comments are closed.