Skip to content
Tutorials Center
My learning

Topics

Lesson 49 of 61 ยท Real-World Dart

Performance and Memory

Make Dart programs fast: JIT versus AOT, const objects, fewer allocations, lazy iterables, StringBuffer, typed data, profiling and honest benchmarks.

Dart is fast out of the box. Its compilers produce efficient machine code, its garbage collector is tuned for programs that create many short-lived objects, and its type system gives the compiler a lot of information. Most programs never need tuning. When one does, the rule is always the same: measure first, change one thing, measure again. Guessing which line is slow is wrong more often than right.

This lesson explains how Dart code runs, then collects the habits that help in the rare hot spot: reusing const objects, avoiding needless allocations, using the right collection and tools for measuring. The Dart code is read-only; the TypeScript stand-ins count work instead of timing it, so their output is the same on every run.

JIT and AOT

Dart has two ways to turn code into something the CPU can run:

  • JIT (just-in-time). The Dart VM compiles code while the program runs. It starts quickly, supports hot reload and debugging, and optimizes the hot parts as it learns how they behave. dart run and Flutter debug builds use JIT.
  • AOT (ahead-of-time). The compiler produces native machine code before the program ever runs. Start-up is immediate and speed is predictable, with no warm-up, and no compiler is shipped. Flutter release builds and dart compile exe use AOT.
TEXT
dart run bin/main.dart                 # JIT, with debugging
dart compile exe bin/main.dart -o app  # AOT, a self-contained executable
dart compile js bin/main.dart          # JavaScript for browsers
dart compile wasm bin/main.dart        # WebAssembly (browser)

The practical consequence for measuring: a debug or JIT run is not representative of what your users get. Numbers from a Flutter debug build can be several times slower than release. Benchmark with dart compile exe (or a Flutter profile build, which is AOT with profiling hooks) before drawing conclusions.

flowchart LR
    SRC["Dart source"] --> K["Kernel<br/>(shared intermediate form)"]
    K --> J["JIT in the VM<br/>fast start, hot reload"]
    K --> A["AOT native code<br/>fast and predictable"]
    K --> W["JavaScript or Wasm<br/>for the browser"]

One front end feeds several back ends. Choose the one that matches the job: develop with JIT, ship with AOT.

Use const to share objects

A const object is built once, at compile time, and canonicalized: every const expression with the same type and the same values refers to one shared instance. Building the same value again with new (or without const) creates a fresh object each time.

DART
void main() {
  const a = Point(1, 2);
  const b = Point(1, 2);
  final c = Point(1, 2); // not const: a separate instance

  print(identical(a, b)); // true, one shared object
  print(identical(a, c)); // false
  print(a == c);          // false unless Point overrides ==
}

class Point {
  final int x, y;
  const Point(this.x, this.y);
}

Marking constructors const and writing const at the call site saves memory and allocation time, and in Flutter it lets whole widget subtrees be skipped during rebuilds. The prefer_const_constructors and prefer_const_literals_to_create_immutables lints find places where you can add it. Look back at static members and const constructors and variables for the rules about what may be const.

TypeScript Canonical instances versus fresh objects (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Allocations and the garbage collector

Dart's garbage collector is generational. New objects are born in a small young generation that is cleaned very quickly, and objects that survive get promoted to an old generation that is cleaned less often. Short-lived objects, such as a temporary record or a small list in a loop, are cheap. Even so, a hot loop that creates millions of them keeps the collector busy, and memory that you hold on to too long moves to the more expensive old generation.

Habits that reduce pressure:

  • Build strings with StringBuffer. s += x in a loop creates a new string each time and copies all earlier text, which makes the loop quadratic.
  • Preallocate when you know the size: List<int>.filled(n, 0), List.generate(n, (i) => i), or List<int>.empty(growable: false). A fixed-length list skips growth and uses less memory.
  • Use typed data for numbers. Uint8List, Int32List and Float64List (from dart:typed_data) store raw values in a compact block, without a box per element. They are the right type for bytes, pixels and audio.
  • Do work once. Move values that do not change out of the loop, and store a computed result in a variable instead of calling an expensive getter repeatedly.
  • Do not hold on to what you do not need. A long-lived cache or a closure that captures a large object keeps it alive. Bound caches by size, and look at WeakReference for entries that may disappear.
DART
import 'dart:typed_data';

String joinNumbers(int count) {
  final buffer = StringBuffer();
  for (var i = 0; i < count; i++) {
    if (i > 0) buffer.write(',');
    buffer.write(i);
  }
  return buffer.toString();
}

Float64List squares(int n) {
  final result = Float64List(n); // one compact block, filled with 0.0
  for (var i = 0; i < n; i++) {
    result[i] = i * i.toDouble();
  }
  return result;
}

Lazy iterables can do the work twice

The methods map, where and expand do not run when you call them. They return a lazy iterable that computes elements each time you walk through it. That is efficient when you read the result once and wasteful when you read it several times:

DART
final prices = [10, 20, 30];
final doubled = prices.map((p) {
  print('computing $p');
  return p * 2;
});

print(doubled.length); // runs the function for every element
print(doubled.first);  // runs it again
print(doubled.toList()); // and again

If you need the values more than once, call toList() a single time and keep the list. Likewise, iterable.length on a lazy iterable is a full walk, not a stored number.

TypeScript Counting repeated work (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Choose the right data structure

The best optimization is often a better algorithm or collection, not a micro-tweak:

Need Use Why
Many "is this in the group?" checks Set Average constant time; list.contains scans every element
Look up by key Map Constant time on average
Add and remove at both ends Queue from dart:collection list.removeAt(0) shifts every remaining element
Sorted order with fast inserts SplayTreeSet / SplayTreeMap Keeps order without re-sorting
Compact numbers or bytes typed lists No per-element object

See lists, sets and maps for the basics. Changing a nested loop that does list.contains into one that checks a Set turns a slow program into a fast one far more reliably than any compiler flag.

Keep the UI free

A Dart program has one thread per isolate, so a long calculation on the main isolate freezes everything that shares it. await does not help here: it only gives time to waiting work. Move CPU-heavy work (parsing a large file, resizing an image) to Isolate.run. Remember the cost of copying the message in and out, and measure that the move helps.

In Flutter, performance work also means rebuilding less: use const widgets, build lists lazily with ListView.builder, and keep expensive work out of build. The next lessons say more about Flutter.

Measuring honestly

Three tools cover most needs.

1. Stopwatch for quick checks.

DART
void main() {
  final watch = Stopwatch()..start();
  final result = work();
  watch.stop();
  print('result=$result in ${watch.elapsedMilliseconds} ms');
}

Run it several times and discard the first run, since JIT warm-up and caches distort it. Make sure the result is used, otherwise the compiler may remove the work.

2. package:benchmark_harness for repeatable benchmarks. It runs your code many times, reports the average per run and handles warm-up, so the numbers are steadier than a single stopwatch reading.

3. DevTools for finding the problem. Run your app in profile mode, open Dart DevTools and use the CPU profiler to see which functions take the time, the memory view to see which objects accumulate and what is retaining them, and the performance view (in Flutter) to see dropped frames. Profile first; then optimize the function the profiler names.

A checklist for any benchmark: use an AOT or profile build, run enough iterations, avoid printing inside the measured code, compare against a baseline, and change only one thing between runs.

flowchart LR
    M["Measure<br/>profile build + DevTools"] --> F["Find the hot spot"]
    F --> C["Change one thing"]
    C --> R["Measure again"]
    R --> D{"Better?"}
    D -->|"yes"| K["Keep it"]
    D -->|"no"| U["Undo it"]
    U --> M
    K --> M

Optimization is a loop. Without the measuring step it is guessing.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which build mode compiles to native code before the program runs?

    AOT produces machine code ahead of time, giving fast start-up and predictable speed. JIT compiles while the program runs.
  2. 2. Given const a = Point(1, 2); const b = Point(1, 2);, what does identical(a, b) return?

    Dart creates one shared instance for const expressions with the same type and values.
  3. 3. Why is s += x inside a long loop a performance risk?

    Use a StringBuffer, which appends in place and builds the final string once.
  4. 4. You call list.map(f) and then read .length and .first of the result. How often does f run?

    map returns a lazy iterable. Call toList() once if you need the results several times.
  5. 5. What is the best first step when a Dart program is slow?

    Measure first. The profiler shows where time and memory go, and guessing is often wrong.

Summary

  • Develop with JIT (hot reload, debugging) and ship with AOT; never judge speed from a debug build.
  • const objects with equal values share one instance, saving allocations and rebuild work.
  • Reduce allocations: StringBuffer, preallocated or typed lists, no repeated work in loops, bounded caches.
  • Lazy iterables (map, where) rerun their work on each walk; call toList() once when you reuse results.
  • Pick the right collection (Set and Map for lookups, Queue for both ends) and move heavy CPU work to an isolate.
  • Measure with Stopwatch, benchmark_harness and DevTools, one change at a time.

Next: from Dart to Flutter and Dart on the server.