CodeBlanks Logo Icon CodeBlanks

Code generation

Learn code generation and backends.

Code generation

Code generation is the stage that turns Kernel into target platform code. Each backend uses its own strategy: dart2js generates JavaScript, dart2wasm WebAssembly, dart native machine code.

During code generation, optimizations are applied: dead code elimination, inlining, constant folding. The backend optimizes code based on the target's characteristics. The output of this stage is an executable file (native) or loadable code for the browser.

Optimizations

Various optimizations are applied during code generation. Dead code elimination removes never-used code. Inlining expands small functions at the call site. Constant folding pre-computes expressions known at compile time.

These optimizations shrink and speed up the output. The backend optimizes based on the target: size for the web, speed for native. Good optimization directly affects user experience.

Practice A Backend class

Define a Backend class with final String name; final String target; Backend(this.name, this.target); field and constructor. Add a String emit() => '$name → $target'; method. In main create final b = Backend('dart2js', 'JavaScript');; print with print(b.emit());.

Starter code

main.dart
void main() {
  // define a Backend class (name, target; emit method)
  // create a Backend; print emit()
}

Sample solution

main.dart
class Backend {
  final String name;
  final String target;
  Backend(this.name, this.target);
  String emit() => '$name → $target';
}

void main() {
  final b = Backend('dart2js', 'JavaScript');
  print(b.emit());
}

Expected output

dart2js → JavaScript

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does the dart2js backend produce?

  • Machine code
  • WebAssembly
  • JavaScript Correct answer
  • Garbage collector

Explanation: dart2js generates JavaScript code.

2 Match the backends

Term Meaning
dart2js JavaScript
dart2wasm WebAssembly
dart native Machine code
VM (JIT) Runtime compilation

3 An optimization name

Question
final opt = '____';
print(opt);
Answer
final opt = 'inlining';
print(opt);

Explanation: inlining expands small functions at the call site.

All lessons in Expert